. Advertisement .
..3..
. Advertisement .
..4..
Python has many in-built libraries that support basic and advanced data structures. The collections module includes classes that support queue, deque, list, and dictionary. In this blog, let’s learn how to count number of keys in dictionary in Python.
How Can You Count Number of Keys in Dictionary in Python?
Utilize len() to count the number of keys in a dictionary in Python. In Dictionary Python, you can count the number of keys by utilizing len(). Let’s take a look at an example:
dict1 = {'R1' : 45,'R2' : 48,'R3' : 50} print(len(dict1.keys()))
Result:
3
Utilize enumerate() to count the number of keys in a dictionary in Python. In the Python dictionary, you can count the number of keys by using enumerate(). Let’s take a look at an example:
dict1 = {'R1' : 45,'R2' : 48,'R3' : 50} def count_keys(dict): count = 0 for i in enumerate(dict): count += 1 return count print(count_keys(dict1))
Result:
3
Option 1: Utilize len()
In Dictionary Python, you can count the number of keys by utilizing len(). Let’s take a look at an example:
dict1 = {'R1' : 45,'R2' : 48,'R3' : 50} print(len(dict1.keys()))
Result:
3
Option 2: Utilize enumerate()
In the Python dictionary, you can count the number of keys by using enumerate(). Let’s take a look at an example:
dict1 = {'R1' : 45,'R2' : 48,'R3' : 50} def count_keys(dict): count = 0 for i in enumerate(dict): count += 1 return count print(count_keys(dict1))
Result:
3
Conclusion
We hope you found our article on counting number of keys in dictionary in Python useful. We understand that dealing with this can be confusing; therefore, we hope that our information has assisted you in doing this. Please leave a comment if you have any further questions or concerns. Thank you for taking the time to read; we are always delighted anytime one of our pieces can give important information on a topic like this!
Leave a comment