Created
March 26, 2015 15:02
-
-
Save perpetual-hydrofoil/3d2c22f6abac31b9aea8 to your computer and use it in GitHub Desktop.
Dictionary comprehensions in Python
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
# 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