Created
March 29, 2019 11:14
-
-
Save elena-roff/4269c63e53a87b6f73594a07be65880b to your computer and use it in GitHub Desktop.
collections Tricks
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
from collections import defaultdict, Counter | |
from typing import Mapping, List | |
""" Most commom element with Counter."" | |
stuff: List = ['book', 'book', 'phone', 'book', 'phone'] | |
cnt = Counter(stuff) | |
# first most common | |
# first element of the list and a tuple | |
cnt.most_common(1)[0][0] | |
# 'book' | |
""" | |
Advanced mapping with default dict. | |
Format: | |
{ | |
key1: { | |
key2: { | |
x: Hotel, | |
y: Counter({key3: n}) | |
} | |
}, | |
} | |
""" | |
data: Mapping = defaultdict( | |
lambda: defaultdict( | |
lambda: { | |
'x': None, | |
'y': Counter() | |
} | |
) | |
) | |
elements: List = [some objects] | |
for el in elements: | |
key1 = el.something | |
key2 = el.something_else | |
key3 = el.something_else_again | |
data[key1][key2]['x'] = el.some_value | |
# counts occurences | |
hotels[key1][key2]['y'].update({key3: 1}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment