KnowledgeBoat Logo
|
LoginJOIN NOW

Computer Science

The following code has two dictionaries with tuples as keys. While one of these dictionaries being successfully created, the other is giving some error. Find out which dictionary will be created successfully and which one will give error and correct it :

dict1 = { (1, 2) : [1, 2], (3, 4) : [3, 4]}  
dict2 = { ([1], [2]) : [1,2], ([3], [4]) : [3, 4]}

Python Dictionaries

18 Likes

Answer

dict1 will be created successfully because tuples are used as keys. As tuples are immutable, therefore it won't give any error.

dict2 will give an error because the tuples used as keys of dict2 contain lists as their elements. As lists are mutable, so they can't appear in keys of the dictionary.

It can be corrected by removing list elements from the tuples as shown below:
dict2 = { (1,2) : [1,2], (3,4) : [3, 4]}

Answered By

14 Likes


Related Questions