Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to convert my list of tuples to the composite-key dictionary so that I can custom and sort it 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

Kindly suggest a solution. 

1 Answer

0 votes
by (36.8k points)
edited by

The dict.update updates the dictionary with a key/value pairs from the other dict. What you are adding is the tuple, not dict. Then change new to:

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

If you are a beginner and want to know more about Python the do check out the Data Science with Python Course 

Browse Categories

...