Exercise 17: Dict Comprehension | HolyPython.com Best way to practice. (original) (raw)
Python Dict Comprehension Exercises
Let’s check out some exercises that will help understand Dict Comprehension better.
Exercise 17-a
Create a dictionary from the list with same key:value pairs, such as: {"key": "key"}.
You can type your dict comprehension inside curly brackets: {}
Your key and value will be the same iterator such as: {i:i for i…}
Then you have to type the remaining part as: in iterable.
dict = {i:i for i in lst}
Exercise 17-b
First, create a range from 100 to 160 with steps of 10.
Second, using dict comprehension, create a dictionary where each number in the range is the key and each item divided by 100 is the value.
You can type your dict comprehension inside curly brackets: {}
i:i/100 should be used to create the needed key:value pairs.
rng = range(100, 160, 10)
dict = {i:i/100 for i in rng}
Exercise 17-c
Using dict comprehension and a conditional argument create a dictionary from the current dictionary where only the key:value pairs with value above 2000 are taken to the new dictionary.
You can type your dict comprehension inside curly brackets: {}
i:dict1[i] should be used to create the needed key:value pairs.
dict2 = {i:dict1[i] for i in dict1 if dict1[i]>2000}
Need More Exercises?
Check out Holy Python AI+ for amazing Python learning tools.
*Includes 14 more programming languages, inspirational tools and 1-on-1 consulting options.
Umut Sagir
Finance & Data Science Professional,
Founder of HolyPython