How do you count the number of items in a dictionary python?

  1. HowTo
  2. Python How-To's
  3. Count Number of Keys in Dictionary Python

Created: January-30, 2021 | Updated: February-07, 2021

  1. Use the len() Function to Count the Number of Keys in a Python Dictionary
  2. Create a User-Defined Function to Calculate the Number of Keys in a Python Dictionary

In this tutorial, we will discuss how to count the number of keys in a Python dictionary using the len() function and also create our own function for the same purpose.

Use the len() Function to Count the Number of Keys in a Python Dictionary

The len() function in Python is used to return the total number of items present in an object. We can use the keys() method of the dictionary to get a list of all the keys in the dictionary and count the total number using len().

dict1 = {'a':1,'b':2,'c':3}
print(len(dict1.keys()))

Output:

3

We can also pass the dictionary directly to the len() function, which returns the distinct total entries in the dictionary, which is the same as the number of the keys.

dict1 = {'a':1,'b':2,'c':3}
print(len(dict1))

Output:

3

Create a User-Defined Function to Calculate the Number of Keys in a Python Dictionary

We can also create our own function to calculate the number of Python keys. We initialize a variable to 0, iterate over the dictionary using the enumerate(), increment the variable in every iteration, and return it. The following code will explain this.

dict1 = {'a':1,'b':2,'c':3}

def count_keys(dict):
    count = 0
    for i in enumerate(dict):
        count += 1
    return count

print(count_keys(dict1))

Output:

3

The enumerate() function returns an enumerate object that attaches a counter variable to the dictionary’s keys and makes looping over the dictionary easily.

Related Article - Python Dictionary

  • Check if a Key Exists in a Dictionary in Python
  • Convert a Dictionary to a List in Python
  • Get All the Files of a Directory
  • Find Maximum Value in Python Dictionary
  • View Discussion

    Improve Article

    Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or not we use the isinstance() method which is inbuilt in Python. isinstance() method takes two parameters:

    object - object to be checked
    classinfo - class, type, or tuple of classes and types

    It return a boolean whether the object is an instance of the given class or not. Let’s discuss different methods to count number of items in a dictionary value that is a list. Method #1 Using in operator 

    Python3

    def main():

        d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],

            'B' : 34,

            'C' : 12,

            'D' : [7, 8, 9, 6, 4] }

        count = 0

        for x in d:

            if isinstance(d[x], list):

                count += len(d[x])

        print(count)

    if __name__ == '__main__':

        main()

      Method #2: Using list comprehension 

    Python3

    def main():

        d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],

            'B' : 34,

            'C' : 12,

            'D' : [7, 8, 9, 6, 4] }

        print(sum([len(d[x]) for x in d if isinstance(d[x], list)]))

    if __name__ == '__main__':

        main()

      Method #3: Using dict.items() 

    Python3

    def main():

        d = { 'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],

            'B' : 34,

            'C' : 12,

            'D' : [7, 8, 9, 6, 4] }

        count = 0

        for key, value in d.items():

            if isinstance(value, list):

                  count += len(value)

        print(count)

    if __name__ == '__main__':

        main()

      Method #4: Using enumerate() 

    Python3

    def main():

        d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],

            'B' : 34,

            'C' : 12,

            'D' : [7, 8, 9, 6, 4] }

        count = 0

        for x in enumerate(d.items()):

            if isinstance(x[1][1], list):

                count += len(x[1][1])

        print(count)

    if __name__ == '__main__':

        main()

    Method#5: Using values(),find() and type().

    Python3

    def main():

        d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],

            'B' : 34,

            'C' : 12,

            'D' : [7, 8, 9, 6, 4] }

        count = 0

        for x in list(d.values()):

            type1=str(type(x))

            if(type1.find('list')!=-1):

                count+=len(x)

        print(count)

    if __name__ == '__main__':

        main()


    How do you find the number of items in a dictionary?

    If you want to find the count number of items stored in a dictionary then you have to use the len() function where items are to be represented as key-value pairs.

    How do you count items in a list in Python?

    The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.