GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Books
  • Mini
  • Tips
  • Tags
  • About
  • learnbyexample
  • Python tip 17: counting frequency of items

This view

  • Original page
  • New address

GeezerVison is showing learnbyexample.github.io — Python tip 17: counting frequency of items

One of the ways to count the frequency of items is to make use of the dict.get() method:

>>> vehicles = ['car', 'jeep', 'car', 'bike', 'bus', 'car', 'bike']
>>> hist = {}
>>> for v in vehicles:
...     hist[v] = hist.get(v, 0) + 1
... 
>>> hist
{'car': 3, 'jeep': 1, 'bike': 2, 'bus': 1}

And here's a solution using the built-in collections module:

>>> from collections import Counter

>>> vehicles = ['car', 'jeep', 'car', 'bike', 'bus', 'car', 'bike']
>>> Counter(vehicles)
Counter({'car': 3, 'bike': 2, 'jeep': 1, 'bus': 1})

>>> Counter('abracadabra')
Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

info See stackoverflow: using a dictionary to count items and stackoverflow: count frequency of elements for more ways to solve this problem.

Video demo:


info See also my 100 Page Python Intro ebook.

#python#tip

← Python tip 18: arbitrary number of arguments

Python tip 16: delete list elements using index or slice →


📰 Use this link for the Atom feed.
✅ Follow me on Twitter, GitHub and Youtube for interesting tech nuggets.


You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.