Skip to content

Instantly share code, notes, and snippets.

@cngkaygusuz
Created August 21, 2014 15:01
Show Gist options
  • Save cngkaygusuz/8ddbc0f096d10f5933b4 to your computer and use it in GitHub Desktop.
Save cngkaygusuz/8ddbc0f096d10f5933b4 to your computer and use it in GitHub Desktop.
Filter a dictionary by certain keys
# 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