D.M
0
Q:

collections.counter in python

>>> from collections import Counter
>>> 
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>> 
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>> 
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]
1
from collections import defaultdict 
  
# Defining a dict containing lists 
d = defaultdict(list) 
  
for i in range(5): 
    d[i].append(i) 
      
print("Dictionary with values as list:") 
print(d) 

#Output:
#Dictionary with values as list:
#defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
2
from collections import OrderedDict 
od = OrderedDict()
1
An OrderedDict is a dictionary subclass that remembers the order 
that keys were first inserted. A regular dict doesn’t track the 
insertion order, and iterating it gives the values in an arbitrary 
order.
# A Python program to demonstrate working of OrderedDict 
from collections import OrderedDict 
d = {} # regular dict
d['a'] = 1
d['b'] = 2
d['c'] = 3
for key, value in d.items(): 
    print(key, value) 
# Output
# ('a', 1)
# ('c', 3)
# ('b', 2)  
od = OrderedDict() # Ordered Dict
od['a'] = 1
od['b'] = 2
od['c'] = 3
for key, value in od.items(): 
    print(key, value) 
# Output
# ('a', 1)
# ('b', 2)
# ('c', 3)
1
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
3
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
1
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)
0

New to Communities?

Join the community