Dictionary Comprehension

Dictionary comprehension in Python basically creates a new dictionary out of an existing dictionary.

A couple of possible reasons for using dictionary comprehensions are: 1. Filtering out some keys/values in our new dictionary 2. Changing keys or values

Excluding a key/value pair in a new dictionary

1
2
3
4
5
6
7
8
9
old_dict = {"Basketball_Points": 50,
                   "Tennis_Points": 2}

# Exclude "Tennis_Points" in the new dictionary.
new_dict = {key: value for key, value in old_dict.items()
                    if key != "Tennis_Points"}

print(new_dict)
--> {'Basketball_Points': 50}

Change the value of all items

1
2
3
4
5
6
7
8
old_dict = {"Basketball_Points": 50,
            "Tennis_Points": 2}

# Increment the values by 5 for all items.
new_dict = {key: value + 5 for key, value in old_dict.items()}

print(new_dict)
--> {'Basketball_Points': 55, 'Tennis_Points': 7}

The old dictionary will not be changed. The new dictionary will be a copy of the old dictionary with any changes that you have specified.