Created
December 25, 2021 10:26
-
-
Save ruslanmv/77679da597302ddbcd460ea2e2834aa9 to your computer and use it in GitHub Desktop.
Tricks with Dictionaries 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
# Categorizing to dicts | |
words = ['apple', 'bat', 'bar', 'atom', 'book'] | |
by_letters = {} | |
for word in words: | |
letter = word[0] | |
by_letters[letter] = by_letters.get(letter, 0) + 1 | |
value = by_letters[letter] | |
print('Letter: {} - Count: {}'.format(letter, value)) | |
by_letters = {} | |
for word in words: | |
letter = word[0] | |
by_letters.setdefault(letter, []).append(word) | |
print(by_letters) | |
# Empty Dict that ready-to-set default values | |
from collections import defaultdict | |
by_letters = defaultdict(list) | |
for word in words: | |
by_letters[word[0]].append(word) | |
print(by_letters) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment