 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
# 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
# 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
# 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