. Advertisement .
..3..
. Advertisement .
..4..
A dictionary is a Python collection that stores data as key-value pairs, and is also known as a map in various computer languages. As such, keys are one-of-a-kind, serving as an index to the values they contain.
This tutorial will cover how to attain keys, values, and items in a Python dictionary count.
Python Dictionary Count – Methods To Conduct
To count the number of keys in a dictionary in Python, we must use the for loop to explore the dictionary. Next, creating a count variable with a value of 0 that will increase with each iteration is the task to get done. The techniques for counting the keys in a dictionary are as follows:
- Use the len() function
- Use for loop
- Create a user-defined function
Use the len() Function
A more concise manner to get the returns of all distinct dictionary keys is indeed to utilize the len() function.
Thanks to this feature, the overall length of a dictionary, or more accurately, the total number of entries in the dictionary will be all that you shall end up retrieving.
Running the code:
list_dictionary = {"dict1": 1, "dict2": 2, "dict3": 3}
print(len(list_dictionary))
Output:
3
Use for Loop
Using a for loop to get the number of keys in a dictionary is another helpful approach you would not wish to miss out on. Let’s look at the example below.
Running the code:
seaAnimals = {"Squid": 86, "Shark": 56, "Crab": 71, "Seal": 29, "Lobster": 65 }
def count_dict(dict):
count = 0
for key,value in dict.items():
count += 1
return count
print(count_dict(seaAnimals))
Output:
5
In the preceding illustration, the dict.items() function returns the object items as a (key, value) tuple. The ‘value’ and ‘key’ variables iterate over the dictionary in this case.
You may also use the print(key) or print(value) commands to print them. That way, the software will count the two keys as one if they are the same.
Create a User-Defined Function
To calculate the number of Python keys, writing our own function is also a great technique to go for.
Here is how to get it done right: First, we set a variable to 0 and use enumerate() to traverse over the dictionary. Then, you will want to increment the variable in each iteration before returning it. And that’s all it takes to complete such a handy task.
Check out the task below to grasp the mechanism more!
Running the code:
exp_dict = {'Mercury':18,'Jupiter':25,'Uranus':29}
def count_dict(dict):
count = 0
for j in enumerate(dict):
count += 1
return count
print(count_dict(exp_dict))
Output:
3
The Bottom Line
Above is our in depth instruction on how to acquire the number of keys employing Python dictionary count. As you must have taken hold of this insight by now, it’s time to get on the road and pave the way yourself.
Hopefully, this post will be of great help to you somehow. See then!
Leave a comment