简体   繁体   English

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

[英]python convert list of tuples to composite key dictionary

I'm trying to convert a list of tuples to a composite-key dictionary so I can custom sort by either first or last:我正在尝试将元组列表转换为复合键字典,以便我可以按第一个或最后一个自定义排序:

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)

outputs:输出:

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

I'm ashamed of how much time I've spent on this.我为我在这件事上花费了多少时间而感到羞耻。 What would you do?你会怎么办? All input will be greatly appreciated.所有输入将不胜感激。 Thank you!谢谢!

dict.update updates a dictionary with the key/value pairs from an other dict. dict.update使用来自其他字典的键/值对更新字典。 What you are adding is a tuple not dict.您添加的是元组而不是字典。 Then change new to:然后将new更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM