简体   繁体   中英

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. What you are adding is a tuple not dict. Then change new to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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