python将元组列表转换为复合键字典

斜视

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

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

我为我在这件事上花费了多少时间而感到羞耻。你会怎么做?所有输入将不胜感激。谢谢!

程序员365

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章