Last active
April 20, 2022 18:45
-
-
Save FerusAndBeyond/74829ea5247b387984a7f2b9fa76de04 to your computer and use it in GitHub Desktop.
Dictionary comprehension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# remove keys | |
a = dict(a=5, b=6, c=7, d=8) | |
remove = set(["c", "d"]) | |
a = { k: v for k,v in a.items() if k not in remove } | |
# a = { "a": 5, "b": 6 } | |
# keep keys | |
a = dict(a=5, b=6, c=7, d=8) | |
keep = remove | |
a = { k: v for k,v in a.items() if k in keep } | |
# a = { "c": 7, "d": 8 } | |
# add to all values | |
a = dict(a=5, b=6, c=7, d=8) | |
a = { k: v+1 for k,v in a.items() } | |
# a = { "a": 6, "b": 7, "c": 8, "d": 9 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment