dedtech.info

Information about computer technology.

Important Python Counter Object Attributes

This blog post will list some important Python counter object attributes. In some of my blog posts, counter objects are a main part of the example.

Returns a view of all unique elements.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.keys())

Returns counts of each element.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.values())

Returns elements and counts pairs.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.items())

Returns the most common elements and counts as a list of tuples.

from collections import Counter
lst = ["apple", "orange", "grape", "apple", "grape", "apple"]
counts = Counter(lst)

print(counts.most_common(2))

Leave a Reply