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

python convert list of tuples to composite key dictionary

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

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

我很惭愧我在这上面花了多少时间。 你会怎么做? 所有输入将不胜感激。 谢谢!

dict.update 用另一个字典中的 key/value 对更新字典。您要添加的是元组而不是字典。然后将new改为:

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