Skip to content

Instantly share code, notes, and snippets.

@BBischof
Created December 18, 2017 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BBischof/3534f19f546a759876efb3c56bbb3ffe to your computer and use it in GitHub Desktop.
Save BBischof/3534f19f546a759876efb3c56bbb3ffe to your computer and use it in GitHub Desktop.
Finally a clean way to update dictionaries in python if you're unsure all keys exist
your_dict = {}
for i in some_iterator:
your_dict[i] = new_value if i not in your_dict else your_dict[i]+new_value
'''a version with the new value coming from a new dict'''
your_dict = {}
for i in some_iterator:
your_dict[i] = new_values[i] if i not in your_dict else your_dict[i]+new_values[i]
'''a kinda dumb example; letter frequencies'''
letter_counts, letters = {}, ['a','b','a','b','a','c']
for l in letters:
letter_counts[l] = 1 if l not in letter_counts else letter_counts[l]+1
'''returns: {'a': 3, 'b': 2, 'c': 1}'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment