Count number of items in a dictionary value that is a list in Python


We are given a Dictionary in which the values from the key value pair itself is a list. In this article we will see a how to count the number of items in this list which are present as values in the dictionary.

With isinstance

Hindi suppose we use isinstance function to find out if the value of the dictionary is a list. Then we increment a count variable whenever isinstance returns true.

Example

 Live Demo

# defining the dictionary
Adict = {'Days': ["Mon","Tue","wed","Thu"],
   'time': "2 pm",
   'Subjects':["Phy","Chem","Maths","Bio"]
   }
print("Given dictionary:\n",Adict)
count = 0
# using isinstance
for x in Adict:
   if isinstance(Adict[x], list):
      count += len(Adict[x])
print("The number of elements in lists: \n",count)

Output

Running the above code gives us the following result −

Given dictionary:
{'Days': ['Mon', 'Tue', 'wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists:
8

With items()

Which items() we loop through each of the element of the dictionary and apply isinstance function to find out if it is a list.

Example

 Live Demo

# defining the dictionary
Adict = {'Days': ["Mon","Tue","wed","Thu"],
   'time': "2 pm",
   'Subjects':["Phy","Chem","Maths","Bio"]
   }
print("Given dictionary:\n",Adict)
count = 0
# using .items()
for key, value in Adict.items():
   if isinstance(value, list):
      count += len(value)
print("The number of elements in lists: \n",count)

Output

Running the above code gives us the following result −

Given dictionary:
{'Days': ['Mon', 'Tue', 'wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists:
8

With enumerate

The enumerate function also expands and lists the items of a dictionary. We apply is instance to find out the values which are lists.

Example

 Live Demo

# defining the dictionary
Adict = {'Days': ["Mon","Tue","wed","Thu"],
   'time': "2 pm",
   'Subjects':["Phy","Chem","Maths","Bio"]
   }
print("Given dictionary:\n",Adict)
count = 0
for x in enumerate(Adict.items()):
   if isinstance(x[1][1], list):
      count += len(x[1][1])
print(count)
print("The number of elements in lists: \n",count)

Output

Running the above code gives us the following result −

Given dictionary:
{'Days': ['Mon', 'Tue', 'wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
8
The number of elements in lists:
8

Updated on: 04-Jun-2020

800 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements