Dictionary Comprehension Flashcards

1
Q

Dictionary comprehension

A

Create dictionaries using an expression
-can replace for loops and certain lambda functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Syntax for dictionary comprehension

A

Dictionary = {key: expression for (key,value) in iterable}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Ways of using dictionary comprehensions

A

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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Example of list comprehension using a function (Dictionary = {key: function(value) for (key,value) in iterable})

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Quick note about items relating to dictionaries

A

When you refer to the total children in a dictionary (keys and values) your refer to them as their ‘items’

Dictionary.items()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly