How to use a dictionary to count the items in a list with Python?

Sometimes, we want to use a dictionary to count the items in a list with Python.

In this article, we’ll look at how to use a dictionary to count the items in a list with Python.

How to use a dictionary to count the items in a list with Python?

To use a dictionary to count the items in a list with Python, we can use a for loop.

For instance, we write

counts = dict()
for i in items:
  counts[i] = counts.get(i, 0) + 1

to create a for loop that loops through the items list.

In it, we add an entry to the counts dict which is set to counts.get(i, 0) + 1 to set the count to 1 is the dict entry with key i` not yet exist.

Otherwise, we increment the existing value by 1.

Conclusion

To use a dictionary to count the items in a list with Python, we can use a for loop.