9

I've applied the Counter function from the collections module to a list. After I do this, I'm not exactly clear as to what the contents of the new data structure would be characterised as. I'm also not sure what the preferred method for accessing the elements is.

I've done something like:

theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
print newList

which returns:

Counter({'blue': 3, 'red': 2, 'yellow': 1})

How do I access each element and print out something like:

blue - 3
red - 2
yellow - 1
Taku
  • 31,927
  • 11
  • 74
  • 85
Victor Brunell
  • 5,668
  • 10
  • 30
  • 46

2 Answers2

16

The Counter object is a sub-class of a dictionary.

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

You can access the elements the same way you would another dictionary:

>>> from collections import Counter
>>> theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> newList = Counter(theList)
>>> newList['blue']
3

If you want to print the keys and values you can do this:

>>> for k,v in newList.items():
...     print(k,v)
...
blue 3
yellow 1
red 2
Andy
  • 49,085
  • 60
  • 166
  • 233
  • 1
    Thanks. That clears up a lot. Is there any way to force the key-value pairs to print in descending order of count? – Victor Brunell Jan 12 '16 at 03:17
  • Dictionaries are unsorted, but you can do some small hoop jumping to make it print in sorted order. See this answer for more information (and the accepted answer for OrderedDictionaries in general): http://stackoverflow.com/a/13990710/189134 – Andy Jan 12 '16 at 03:19
  • Thanks. That's a big help. I think I found a solution by changing your code from newList.items() to newList.most_common(). – Victor Brunell Jan 12 '16 at 03:21
0

If you want Colors count in descending order you can try like below

from collections import OrderedDict
theList = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
newList = Counter(theList)
sorted_dict = OrderedDict(sorted(newList.items(), key = lambda kv : kv[1], reverse=True))
for color in sorted_dict: 
    print (color, sorted_dict[color]) 

Output:

blue 3
red 2
yellow 1
San
  • 363
  • 3
  • 11