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
123456789
old_dict={"Basketball_Points":50,"Tennis_Points":2}# Exclude "Tennis_Points" in the new dictionary.new_dict={key:valueforkey,valueinold_dict.items()ifkey!="Tennis_Points"}print(new_dict)-->{'Basketball_Points':50}
Change the value of all items
12345678
old_dict={"Basketball_Points":50,"Tennis_Points":2}# Increment the values by 5 for all items.new_dict={key:value+5forkey,valueinold_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.