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
Which of the following will result in an error for a given valid dictionary D?
- D + 3
- D * 3
- D + {3 : "3"}
- D.update( {3 : "3"})
- D.update { {"3" : 3}}
- D.update("3" : 3)
The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}Nesting of dictionary allows you to store a dictionary inside another dictionary. Then why is following code raising error ? What can you do to correct it ?
d1 = {1 : 10, 2 : 20, 3 : 30} d2 = {1 : 40, 2 : 50, 3 : 60} d3 = {1 : 70, 2 : 80, 3 : 90} d4 = {d1 : "a", d2 : "b", d3 : "c"}
Why is following code not giving correct output even when 25 is a member of the dictionary?
dic1 = {'age': 25, 'name': 'xyz', 'salary': 23450.5} val = dic1['age'] if val in dic1: print("This is member of the dictionary") else : print("This is not a member of the dictionary")