【问题标题】:python convert list of tuples to composite key dictionarypython将元组列表转换为复合键字典
【发布时间】:2020-10-20 01:33:04
【问题描述】:

我正在尝试将元组列表转换为复合键字典,以便我可以按第一个或最后一个自定义排序:

def phone(first,last,number):
    directory = dict()
    while True: 
        first = input('enter first: ')
        if first == 'done':
            print('done')
            break
        last = input('enter last: ')
        number = input('enter number: ')
        directory[last,first] = number
        new = {((last,first), number)}
        directory.update(new)

    print(directory)   # unit test

phone(first,last,number)

输出:

enter first: 'ricky'
enter last: 'bobby'
enter number: 1111
Traceback (most recent call last):
  File "py4e.tuples.directory.function.1.py", line 21, in <module>
    phone('first','last','number')
  File "py4e.tuples.directory.function.1.py", line 17, in phone
    directory.update(new)
TypeError: cannot convert dictionary update sequence element #1 to a sequence

我为自己在这方面花费了多少时间感到羞愧。 你会怎么做? 所有输入将不胜感激。 谢谢!

【问题讨论】:

  • 谢谢你;它超级笨重,我知道。你会如何减少它?
  • 我认为,如果您提供一段其他人无需手动输入数据即可运行的代码,将会有很大帮助。即,定义一个仅包含逻辑且不尝试从输入中读取数据的函数,并在硬编码数据上调用此函数来说明您的问题。
  • 在单元测试中自动化是一件好事。谢谢

标签: python dictionary tuples composite-key


【解决方案1】:

dict.update 使用来自其他字典的键/值对更新字典。您要添加的是元组而不是字典。然后把new改成:

new = {((last,first), number)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2015-04-03
    • 2018-02-08
    • 2013-04-01
    相关资源
    最近更新 更多