Dictionary comprehension
A dictionary comprehension is very similar to a list comprehension. The difference is that the final result is a dictionary instead of a list. Recall that each element in a dictionary has 2 parts, a key and a value, which is separated by a colon.
The following dictionary comprehension squares all values in a list:
x = [['a', 1], ['b', 2], ['c', 3], ['d', 4]]
print({key:(value**2) for (key, value) in x})
{'a': 1, 'b': 4, 'c': 9, 'd': 16}
Note:
- When you print a dictionary, the insertion-order of elements is preserved.
- Dictionary comprehensions are wrapped inside
{ }
.
This exercise is part of the course
Python for R Users
Exercise instructions
- Inspect the contents of the 2D list
twitter_followers
in the shell. - Write a dict comprehension where the key is first element of the sub-list, and the value is the second:
tf_dict
. - Print
tf_dict
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Write a dict comprehension
tf_dict = {____:____ for ____,____ in ____}
# Print tf_dict
print(____)