Created
December 18, 2017 05:59
-
-
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
This file contains hidden or 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
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