Skip to content

Instantly share code, notes, and snippets.

@ruslanmv
Created December 25, 2021 10:26
Show Gist options
  • Save ruslanmv/77679da597302ddbcd460ea2e2834aa9 to your computer and use it in GitHub Desktop.
Save ruslanmv/77679da597302ddbcd460ea2e2834aa9 to your computer and use it in GitHub Desktop.
Tricks with Dictionaries in Python
# 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