Skip to content

Instantly share code, notes, and snippets.

@elena-roff
Created March 29, 2019 11:14
Show Gist options
  • Save elena-roff/4269c63e53a87b6f73594a07be65880b to your computer and use it in GitHub Desktop.
Save elena-roff/4269c63e53a87b6f73594a07be65880b to your computer and use it in GitHub Desktop.
collections Tricks
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