Enrollments started for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 5 Seats Left
Apply NowLogin using Social Account
     Continue with GoogleLogin using your credentials
There is a function with the name items
associated with dictionaries that returns a list of tuples, where each tuple is a key-value pair:
d = { "one" : 1, "two" : 2, "three" : 3}
k = d.items()
print(k)
It prints dict_items([('one', 1), ('two', 2), ('three', 3)])
. We can cast to list using list
,
l = list(k)
print(l)
It prints a list of tuples [('one', 1), ('two', 2), ('three', 3)]
.
Since it is a dictionary, the items are in no particular order.
However, since the list of tuples is a list, and tuples are comparable, we can now sort the list of tuples. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key.
We can print the content of the dictionary with below code
for key, value in list(k):
print(key, value)
It prints,
one 1
two 2
three 3
dict_tuple_func
that takes a list of integers as an argument. Sample Input -
dict_tuple_func([1, 2, 3, 1, 2, 3])
Sample Output -
({1: 2, 2: 2, 3: 2}, 6)
Please note output is the tuple in which first element is the dictionary and the second element is the sum of all the unique integers in the list.
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
Note - Having trouble with the assessment engine? Follow the steps listed here
Loading comments...