Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b986873

Browse files
Create 12_Dictionary_Comprehension.MD
1 parent 3b4d25a commit b986873

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# **Dictionary Comprehension**
2+
Create dictionaries using an expression can replace for loop and certain lambda functions
3+
4+
**Syntax:**
5+
* `dictionary = {key: expression for {key,value} in iterable}`
6+
* `dictionary = {key: expression for {key,value} in iterable if conditional}`
7+
* `dictionary = {key: (if/else) for {key,value} in iterable}`
8+
* `dictionary = {key: function(value) for {key, value} in iterable}`
9+
10+
```py
11+
cities_in_F = {'New York': 32, 'Boston': 22, 'Los Angeles': 100, 'Chicago': 50}
12+
cities_in_C = {key: ((value - 32)+(5/9)) for (key,value) in cities_in_F.items()}
13+
print(cities_in_C)
14+
15+
Weather = {'New York': 'Snowing', 'Boston': 'Rainy', 'Los Angeles': 'Sunny', 'Chicago': 'Cloudy'}
16+
sunny_weather = {key: value for (key,value) in Weather.items() if value == 'Sunny'}
17+
print(sunny_weather)
18+
19+
desc_cities = {key: ("WARM" if value >= 40 else "COLD") for (key,value) in cities_in_F.items()}
20+
print(desc_cities)
21+
22+
desc_cities_1 = {key: check_temp(values) for (key,values) in cities_in_F.items()}
23+
print(desc_cities_1)
24+
def check_temp(values):
25+
if values>=70:
26+
return "HOT"
27+
elif 69<=values>=40:
28+
return "WARM"
29+
else:
30+
return "COLD"
31+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /