Access contents of list after applying Counter from collections module
22,952
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
Author by
Victor Brunell
Updated on August 02, 2022Comments
-
Victor Brunell over 1 year
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
-
Victor Brunell over 8 yearsThanks. That clears up a lot. Is there any way to force the key-value pairs to print in descending order of count?
-
Andy over 8 yearsDictionaries 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): stackoverflow.com/a/13990710/189134
-
Victor Brunell over 8 yearsThanks. That's a big help. I think I found a solution by changing your code from newList.items() to newList.most_common().