What order do the keys print in after the following code is run?counts = {'annie' : 42, 'chuck' : 1, 'jan' : 100}items = counts.items()sorted(items, key = lambda t: t[1])for item in items: print(item[0]) jan, chuck, annie chuck, annie, janannie, chuck, janjan, annie, chuck
Question
What order do the keys print in after the following code is run?counts = {'annie' : 42, 'chuck' : 1, 'jan' : 100}items = counts.items()sorted(items, key = lambda t: t[1])for item in items: print(item[0]) jan, chuck, annie chuck, annie, janannie, chuck, janjan, annie, chuck
Solution
The keys will print in the order they were originally added to the dictionary, which is 'annie', 'chuck', 'jan'. This is because dictionaries in Python are ordered collections since version 3.7.
Here's the step by step explanation:
-
The dictionary
countsis created with keys 'annie', 'chuck', and 'jan' and corresponding values 42, 1, and 100. -
The
items()method is called oncountswhich returns a view object that displays a list of a dictionary's key-value tuple pairs. This is assigned to the variableitems. -
The
sorted()function is called withitemsas the argument and a lambda function as the key which sorts the items by their values. However, this sorted list is not assigned to any variable, so it is not used in the following code. -
A for loop is used to iterate over
itemsand print the keys. Sinceitemswas not updated after being sorted, the keys are printed in the order they were originally added to the dictionary.
So, the output will be:
annie
chuck
jan
Similar Questions
The elements of a list are arranged in descending order.Which of the following two will give same outputs? i. print(list_name.sort()) ii. print(max(list_name)) iii. print(list_name.reverse()) iv. print(list_name[-1])
What is the order of precedence in python?
What will be the output of the following Python code snippet?a={1:"A",2:"B",3:"C"}for i,j in a.items(): print(i,j,end=" ")1 A 2 B 3 C1 2 3A B C1:”A” 2:”B” 3:”C”
Write a Python program to sort a dictionary – Based on the ValuesConstraints:Input Format:DictionaryOutput Format:After Sorting - Key and Value needs to be printed one by one with a space separating each<Key> <Value>Example:Input:{2: 56, 1: 12, 5: 122, 4: 24, 6: 18, 3: 323}Output:1 126 184 242 565 1223 323 Explanation:NAPublic Test Cases:# INPUT EXPECTED OUTPUT1 {2: 56, 1: 12, 5: 122, 4: 24, 6: 18, 3: 323}1 126 184 242 565 1223 323
my_first_list = ['a', 'b', 'c']my_second_list = ['d', 'e', 'f', 'g']my_third_list = my_second_list + my_first_listmy_third_list.pop()my_third_list.sort()print (my_third_list)
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.