How to Count the Contents of a Dictionary in Python

Python is a free, open-source, object oriented programming language. When programming in Python, you may need to count the amount of times an object occurs in a dictionary. A dictionary is a Python data structure similar to associative arrays in other programming languages, like "C." To count the number of instances of an object in a dictionary, import the built-in Python module, "Collections" and call the "Counter" function.

Instructions

    • 1

      Access your Python editor.

    • 2

      Import the "Collections" module and the "Counter" function by typing:

      from collections import Counter

    • 3

      Enter the contents of your library. For example, type:

      itemDict = (['cat', 'cat', 'dog', 'fish', 'horse', 'fish', 'cat', 'dog'])

    • 4

      Count the occurrences of each string object in the dictionary, "itemDict" by typing:

      Counter(itemDict)

    • 5

      Press "Enter". Continuing the example, Python returns:

      Counter({'cat': 3, 'fish': 2, 'dog': 2, 'horse': 1})

      In this example, Python returns the string object, then the number of instances of that object in the dictionary. For example, there are three occurrences of 'cat' in 'itemDict.'

      Note that Counter returns the string objects in ascending order. In this example, 'fish" is returned before 'dog' because Python counted two instances of 'fish" before it found two instances of 'dog'.

Related Searches:

References

Comments

Related Ads

Featured