- Python Dictionary Count using Various Methods
- Get Python Dictionary Count
- Method-1: Python Dictionary Count using the len() function
- Method-2: Python Dictionary Count using the for loop
- Method-3: Python Dictionary Count using the dict.keys()
- Method-4: Python Dictionary Count using the dict.items()
- Method-5: Python Dictionary Count using the list comprehension
- Method-6: Python Dictionary Count using the enumerate() function
- Python count keys in dict
- # Count the number of Keys in a Dictionary in Python
- # Explicitly using the dict.keys() method
- # Using a for loop to count the number of keys in a dictionary
- # Count the number of dictionary keys with values matching condition
- # Checking if the dictionary is empty
- # Additional Resources
Python Dictionary Count using Various Methods
In this Python tutorial, we will study the Python dictionary Count using some examples in python.
In Python, a dictionary is a data structure that stores key-value pairs. The number of keys in a dictionary can be determined using 6 methods.
- Using the len() function
- Using the for loop
- Using the dict.keys()
- Using the dict.items()
- Using the list comprehension
- Using the enumerate() function
Get Python Dictionary Count
Here we will discuss and understand how to determine the number or count of Dictionary keys.
Let us understand the first method using the len() function in Python.
Method-1: Python Dictionary Count using the len() function
In this method, we will use the len() function to determine the number of keys in a dictionary. The len() function returns the number of items in a list-like object, including dictionaries.
# create a dictionary with keys and values countries = # find the number of keys in the dictionary using the len() function count = len(countries) # print the count print(count)
Method-2: Python Dictionary Count using the for loop
In this method, we will use a for loop to loop through the keys in the dictionary and increment a counter variable for each key. This will give us the number of keys in the dictionary.
# create a dictionary with keys and values countries = # initialize a variable to count the number of keys count = 0 # loop through the keys in the dictionary for key in countries: # increment the count for each key count += 1 # print the count print(count)
The above code demonstrates how to count the number of keys in a dictionary using a for loop.
- First, a dictionary named countries is created with key-value pairs.
- Then, a variable named count is initialized to store the number of keys in the dictionary.
- A for loop is used to loop through the keys in the countries dictionary using the for key in countries: syntax.
- Inside the for loop, the count variable is incremented by 1 for each iteration.
- After the for loop, the value of the count is printed to the console using the print() function.
Method-3: Python Dictionary Count using the dict.keys()
In this method, we will use the dict.keys() method to get a list-like object containing the keys of the dictionary, and use the len() function to determine the number of keys.
# create a dictionary with keys and values countries = # find the number of keys in the dictionary using the dict.keys() method and the len() function count = len(countries.keys()) # print the count print(count)
The above code demonstrates how to count the number of keys in a dictionary using the dict.keys() method and the len() function.
- First, a dictionary named countries are created with key-value pairs.
- Then, the dict.keys() method is used to extract the keys from the dictionary as a list.
- The len() function is used to determine the number of items in the list, which gives us the number of keys in the countries dictionary.
- The result is then stored in a variable named count.
- Finally, the value of the count is printed to the console using the print() function.
Method-4: Python Dictionary Count using the dict.items()
In this method, we will use the dict.items() method to get a list-like object containing the items of the dictionary, and use the len() function to determine the number of items, which will give us the number of keys in the dictionary.
# create a dictionary with keys and values countries = # find the number of keys in the dictionary using the dict.items() method and the len() function count = len(countries.items()) # print the count print(count)
The above code demonstrates how to count the number of keys in a dictionary using the dict.items() method and the len() function.
- First, a dictionary named countries are created with key-value pairs.
- Then, the dict.items() method is used to extract the key-value pairs from the dictionary as a list of tuples.
- The len() function is used to determine the number of tuples in the list, which gives us the number of key-value pairs in the countries dictionary.
- The result is then stored in a variable named count.
- Finally, the value of the count is printed to the console using the print() function.
Method-5: Python Dictionary Count using the list comprehension
In this method, we will use a list comprehension to extract the keys from the dictionary and get the length of the resulting list using the len() function. This will give us the number of keys in the dictionary.
# Define the dictionary named country country = # Use list comprehension to extract the keys from the dictionary and store it in the result list result = len(Python count keys in dict) # Print the result, which is the number of keys in the dictionary print("Number of keys in the dictionary:", result)
The above code uses a list comprehension to count the number of keys in a dictionary.
- First, a dictionary named country are created with key-value pairs.
- Then, a list comprehension is used to extract the keys from the dictionary. The list comprehension Python count keys in dict creates a new list result that contains all the keys from the country dictionary.
- Finally, the len() function is used to determine the number of items in the list, which gives us the number of keys in the country dictionary.
- The result is then printed to the console using the print() function.
Method-6: Python Dictionary Count using the enumerate() function
In this method, we will use enumerate() to loop over the keys in a dictionary and keep track of the number of keys. By using len() with enumerate(), we can find the number of keys in a dictionary.
# create a dictionary with keys and values countries = # find the number of keys in the dictionary using the enumerate() function and the len() function count = len(Python count keys in dict) # print the count print(count)
The above code demonstrates how to count the number of keys in a dictionary using the enumerate() function.
- First, a dictionary named countries is created with key-value pairs.
- Then, the enumerate() function is used to enumerate the keys in the countries dictionary.
- The enumerate() function returns a list of tuples, where each tuple contains an index and a key from the dictionary.
- The length of the list returned by enumerate() is then found using the len() function and stored in a variable named count.
- Finally, the value of the count is printed to the console using the print() function.
You may also like to read the following Python tutorials.
In this Python tutorial, we have learned the implementation of Python Dictionary Count using the following method in python:
- Using the len() function
- Using the for loop
- Using the dict.keys()
- Using the dict.items()
- Using the list comprehension
- Using the enumerate() function
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Python count keys in dict
Last updated: Feb 18, 2023
Reading time · 3 min
# Count the number of Keys in a Dictionary in Python
Use the len() function to count the number of keys in a dictionary, e.g. result = len(my_dict) .
The len() function can be passed a collection such as a dictionary and will return the number of key-value pairs in the dictionary.
Copied!my_dict = 'name': 'Bobby Hadz', 'age': 30, 'tasks': ['dev', 'test'] > result_1 = len(my_dict) print(result_1) # 👉️ 3 result_2 = len(my_dict.keys()) print(result_2) # 👉️ 3
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
The first example shows how to get the number of key-value pairs in the dictionary.
Copied!my_dict = 'name': 'Bobby Hadz', 'age': 30, 'tasks': ['dev', 'test'] > result_1 = len(my_dict) print(result_1) # 👉️ 3
The number of keys and values in the dictionary is the same, so passing the entire dictionary to the len() function is sufficient.
# Explicitly using the dict.keys() method
The dict.keys method returns a new view of the dictionary’s keys.
Copied!my_dict = 'id': 1, 'name': 'Bobby Hadz'> print(my_dict.keys()) # 👉️ dict_keys(['id', 'name']) print(len(my_dict.keys())) # 👉️ 2
You can use the list() class if you need to convert the view of keys into a list.
Copied!my_dict = 'id': 1, 'name': 'Bobby Hadz'> list_of_keys = list(my_dict.keys()) print(list_of_keys) # 👉️ ['id', 'name'] print(len(list_of_keys)) # 👉️ 2
Note that passing the dictionary directly to the len() function is a little faster than creating a view object via the dict.keys() method and passing the view to the len() function.
# Using a for loop to count the number of keys in a dictionary
You can also use a for loop to count the number of keys in a dictionary.
Copied!my_dict = 'name': 'Bobby Hadz', 'age': 30, 'tasks': ['dev', 'test'] > count = 0 for key, value in my_dict.items(): count += 1 print(key, value) print(count) # 👉️ 3
We used a for loop to iterate over the dictionary’s items and on each iteration, we increment the count variable.
The dict.items method returns a new view of the dictionary’s items ((key, value) pairs).
Copied!my_dict = 'id': 1, 'name': 'BobbyHadz'> # 👇️ dict_items([('id', 1), ('name', 'BobbyHadz')]) print(my_dict.items())
If you don’t need to access the key and value while iterating, iterate over the dictionary directly.
Copied!my_dict = 'name': 'Bobby Hadz', 'age': 30, 'tasks': ['dev', 'test'] > count = 0 for key in my_dict: count += 1 print(key) print(count) # 👉️ 3
On each iteration, we get access to the key in the for loop and increment the value of the count variable.
# Count the number of dictionary keys with values matching condition
You can also use a for loop if you need to count the number of dictionary keys with a particular value.
Copied!my_dict = 'a': 1, 'b': 10, 'c': 30, > count = 0 for key, value in my_dict.items(): if value > 5: count += 1 print(key, value) print(count) # 👉️ 2
We used a for loop to iterate over the dictionary’s items.
On each iteration, we check if the current value is greater than 5 .
If the condition is met, we increment the count .
The dictionary has 2 keys that have values greater than 5 , so the count variable stores a value of 2 after the last iteration.
# Checking if the dictionary is empty
You can also use the len() function to check if a dictionary is empty.
Copied!my_dict = > if len(my_dict) == 0: # 👇️ this runs print('dict is empty') else: print('dict is not empty')
If a dictionary has a length of 0 , then it’s empty.
You might also see examples online that check whether the dictionary is truthy (to check if it contains at least 1 key-value pair), which is more implicit.
Copied!my_dict = > if my_dict: print('dict is NOT empty') else: # 👇️ this runs print('dict is empty')
All values that are not truthy are considered falsy. The falsy values in Python are:
- constants defined to be falsy: None and False .
- 0 (zero) of any numeric type
- empty sequences and collections: «» (empty string), () (empty tuple), [] (empty list), <> (empty dictionary), set() (empty set), range(0) (empty range).
Notice that an empty dictionary is a falsy value, so if the dict is empty, the else block is run.
If you need to check if the dictionary is empty using this approach, you would negate the condition with not .
Copied!my_dict = > if not my_dict: # 👇️ this runs print('dict is empty') else: print('dict is NOT empty')
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.