Skip to content

Instantly share code, notes, and snippets.

@FerusAndBeyond
Last active April 20, 2022 18:45
Show Gist options
  • Save FerusAndBeyond/74829ea5247b387984a7f2b9fa76de04 to your computer and use it in GitHub Desktop.
Save FerusAndBeyond/74829ea5247b387984a7f2b9fa76de04 to your computer and use it in GitHub Desktop.
Dictionary comprehension
# 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