Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count number of items in a dictionary value that is a list in Python
Sometimes we have a dictionary where some values are lists and we need to count the total number of items across all these list values. Python provides several approaches to achieve this using isinstance() to check if a value is a list.
Using isinstance() with Dictionary Keys
We can iterate through dictionary keys and use isinstance() to identify list values ?
# defining the dictionary
data_dict = {'Days': ["Mon","Tue","Wed","Thu"],
'time': "2 pm",
'Subjects':["Phy","Chem","Maths","Bio"]
}
print("Given dictionary:\n", data_dict)
count = 0
# using isinstance
for key in data_dict:
if isinstance(data_dict[key], list):
count += len(data_dict[key])
print("The number of elements in lists:", count)
Given dictionary:
{'Days': ['Mon', 'Tue', 'Wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists: 8
Using items() Method
With items() we can directly access both keys and values, making the code more readable ?
# defining the dictionary
data_dict = {'Days': ["Mon","Tue","Wed","Thu"],
'time': "2 pm",
'Subjects':["Phy","Chem","Maths","Bio"]
}
print("Given dictionary:\n", data_dict)
count = 0
# using .items()
for key, value in data_dict.items():
if isinstance(value, list):
count += len(value)
print("The number of elements in lists:", count)
Given dictionary:
{'Days': ['Mon', 'Tue', 'Wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists: 8
Using List Comprehension
A more concise approach using list comprehension and sum() ?
# defining the dictionary
data_dict = {'Days': ["Mon","Tue","Wed","Thu"],
'time': "2 pm",
'Subjects':["Phy","Chem","Maths","Bio"]
}
print("Given dictionary:\n", data_dict)
# using list comprehension
count = sum(len(value) for value in data_dict.values() if isinstance(value, list))
print("The number of elements in lists:", count)
Given dictionary:
{'Days': ['Mon', 'Tue', 'Wed', 'Thu'], 'time': '2 pm', 'Subjects': ['Phy', 'Chem', 'Maths', 'Bio']}
The number of elements in lists: 8
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Dictionary keys | Good | Standard | When you need key information |
items() |
Excellent | Standard | Most readable approach |
| List comprehension | Good | Fast | Concise one-liner solution |
Conclusion
Use items() for the most readable code when counting dictionary list values. List comprehension provides a concise alternative for simple counting operations.
Advertisements
