|
| 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