Computer Science
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")
Python Dictionaries
18 Likes
Answer
The code is not giving the desired output because 25 is present in dic1 as a value and not as a key. "val in dic1" only checks val in the keys of dictionaries.
We can get the desired output by changing val in dic1 to val in dic1.values().
Answered By
11 Likes
Related Questions
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]}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"}What is the output produced by the following code :
d1 = {5 : [6, 7, 8], "a" : (1, 2, 3)} print(d1.keys()) print(d1.values())Consider the following code and then answer the questions that follow :
myDict = {'a' : 27, 'b' : 43, 'c' : 25, 'd' : 30} valA ='' for i in myDict : if i > valA : valA = i valB = myDict[i] print(valA) #Line1 print(valB) #Line2 print(30 in myDict) #Line3 myLst = list(myDict.items()) myLst.sort() #Line4 print(myLst[-1]) #Line5- What output does Line 1 produce ?
- What output does Line 2 produce ?
- What output does Line 3 produce ?
- What output does Line 5 produce ?
- What is the return value from the list sort( ) function (Line 4) ?