Created
August 21, 2014 15:01
-
-
Save cngkaygusuz/8ddbc0f096d10f5933b4 to your computer and use it in GitHub Desktop.
Filter a dictionary by certain keys
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
# This code fails because you cannot change a dictionary's size during iteration. | |
bar = {1: "a", | |
2: None, | |
3: "c" | |
} | |
for key, value in bar.iteritems(): | |
if value is None: | |
bar.pop(key) | |
# This code achieves the same result, but works. | |
# Keep in mind, padding function calls' arguments with spaces are not compliant with pep8. | |
newdict = dict( (key, value) for key, value in bar.iteritems() if key is not None ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment