Example 1: python ordereddict
>>>
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>>
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
Example 2: counter most_common
most_common([n])¶
Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.
Elements with equal counts are ordered arbitrarily:
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
Example 3: python counter
sum(c.values())
c.clear()
list(c)
set(c)
dict(c)
c.items()
Counter(dict(list_of_pairs))
c.most_common()[:-n-1:-1]
c += Counter()
Example 4: python collections to dictionary
list = ["a","c","c","a","b","a","a","b","c"]
cnt = Counter(list)
od = OrderedDict(cnt.most_common())
for key, value in od.items():
print(key, value)
Example 5: python collections
a = collections.defaultdict(list)
a = collections.defaultdict(int)
a = collections.defaultdict(dict)
'''
Example:
In a regular dictionary, if you did the following:
a = {}
if a['apple'] == 1:
return True
else:
return False
You'd get an error, because 'apple' does not exist in dictionary.
However, if you use collections:
a = collections.defaultdict(int)
if a['apple'] == 1:
return True
else:
return False
This would not give an error, and False would be returned.
Also, the dictionary would now have the key 'apple' with a
default integer value of 0 inside it.
If you used say, collections.defaultdict(list), the default value
would be an empty list instead of 0.
'''
Example 6: python collections
list = [1,2,3,4,1,2,6,7,3,8,1]
Counter(list)