Dictionary Comprehension Flashcards
Dictionary comprehension
Create dictionaries using an expression
-can replace for loops and certain lambda functions
Syntax for dictionary comprehension
Dictionary = {key: expression for (key,value) in iterable}
Ways of using dictionary comprehensions
Dictionary = {key: expression for (key,value) in iterable}
Dictionary = {key: expression for (key,value) in iterable if conditional}
Dictionary = {key: (if/else) for (key,value) in iterable}
Dictionary = {key: function(value) for (key,value) in iterable}
Example of list comprehension using a function (Dictionary = {key: function(value) for (key,value) in iterable})
Def check_temp(value):
If value >= 70
Return ‘HOT’
elif 69 >= value >= 40
Return ‘warm’
else:
Return ‘cold’
cities = {‘New York’: 32, ‘Boston’: 75, ‘Los Angeles’: 100,
‘Chicago’: 50}
desc_cities = {key: check_temp (value) for (key, value) in cities. items ()}
print (desc _cities)
Quick note about items relating to dictionaries
When you refer to the total children in a dictionary (keys and values) your refer to them as their ‘items’
Dictionary.items()