Last active
March 3, 2020 14:55
-
-
Save shubhamagarwal92/d81617df10ed71831fb86d6a0102980b to your computer and use it in GitHub Desktop.
maintain a counter of items using dic
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
from collections import defaultdict | |
# method 1 | |
my_dict = defaultdict(int) | |
my_dict[key] += 1 | |
# method 2 | |
my_dict = {} | |
my_dict[key] = my_dict.get(key, 0) + 1 | |
# method 3 | |
from collections import Counter | |
Counter(['apple','red','apple','red','red','pear']) | |
# Be careful if you want to store list as default value | |
# https://stackoverflow.com/questions/5772148/python-using-dictionary-get-method-to-return-empty-list-by-default-returns-none | |
# Use something like: | |
dict = defaultdict(list) | |
dict[i].append( j ) | |
# To get sorted | |
# https://stackoverflow.com/questions/20950650/how-to-sort-counter-by-value-python | |
from collections import Counter | |
x = Counter({'a':5, 'b':3, 'c':7}) | |
x.most_common() | |
from collections import Counter, OrderedDict | |
x = Counter({'a':5, 'b':3, 'c':7}) | |
y = OrderedDict(x.most_common()) | |
# Pandas df | |
import pandas as pd | |
pd.DataFrame.from_dict(data) | |
# or | |
>>> data = {'row_1': [3, 2, 1, 0], 'row_2': ['a', 'b', 'c', 'd']} | |
pd.DataFrame.from_dict(data, orient='index') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment