Skip to content

Instantly share code, notes, and snippets.

@perpetual-hydrofoil
Created March 26, 2015 15:02
Show Gist options
  • Save perpetual-hydrofoil/3d2c22f6abac31b9aea8 to your computer and use it in GitHub Desktop.
Save perpetual-hydrofoil/3d2c22f6abac31b9aea8 to your computer and use it in GitHub Desktop.
Dictionary comprehensions in Python
# python 2.7 and later now allows list comprehensions against dictionaries too!
foo = {"alice": "camper", "joe": "medic", "paul": "sniper"}
# Now, you can do dictionary comprehensions like this (2.7):
bar = {first: last for first,last in foo.items() if last not in ["camper", "sniper"]}
# or, you can do it the old way:
baz = dict([(first, last) for first,last in foo.items() if last.lower() not in ["camper", "sniper"]])
# In each case, the result is:
print {'joe': 'medic'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment