Computer Science
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) ?
Python Dictionaries
17 Likes
Answer
- The output of line 1 is :
'd' - The output of line 2 is:
30 - The output of line 3 is:
False
Since 30 is present in myDict as a value and not as a key. - The output of line 5 is:
('d',30)myLstis a list which is created by dictionary items i.emyDict.items()
Hence, myLst will store ⇒[('a', 27), ('b', 43), ('c', 25), ('d', 30)]myLst.sort()will sort the list in ascending order according to the first element of each tuple. Since the first elements of the tuples are all strings, Python performs lexicographical sorting, which means that 'a' comes before 'b' and so on.myLst[-1]will return last element of list i.e.,('d', 30). - The sort function in Line 4 will not return any value.
It will sort myLst in place in ascending order according to the first element of each tuple. Since the first elements of the tuples are all strings, Python performs lexicographical sorting, which means that 'a' comes before 'b' and so on. The sorted myLst will be[('a', 27), ('b', 43), ('c', 25), ('d', 30)]
Answered By
12 Likes
Related Questions
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")What is the output produced by the following code :
d1 = {5 : [6, 7, 8], "a" : (1, 2, 3)} print(d1.keys()) print(d1.values())What will be the output produced by following code ?
d1 = { 5 : "number", "a" : "string", (1, 2): "tuple" } print("Dictionary contents") for x in d1.keys(): # Iterate on a key list print (x, ':' , d1[x], end = ' ') print (d1[x] * 3) print ( )Predict the output:
d = dict() d['left'] = '<' d['right'] = '>' print('{left} and {right} or {right} and {left}')