Kodeclik Blog
Python Dictionary Length
Dictionaries are very useful data structures that can hold key-value pairs. Here is an example of a dictionary that stores months and the number of days in each.
calendar = {'January': 31,
'February': 28,
'March': 31,
'April': 30,
'May': 31,
'June': 30,
'July': 31,
'August': 31,
'September': 30,
'October': 31,
'November': 30,
'December': 31}
Note that the keys are strings representing names of months. The values are integers denoting the number of days in the respective month.
Finding the length of the dictionary
Use the len() function on the dictionary to find its length. For instance:
print("Length of the calendar dictionary is: ", len(calendar))
This outputs:
Length of the calendar dictionary is: 12
Find the length of a dictionary’s keys
We can use the same approach to first extract the keys of the dictionary and then apply len() on that result. Needless to say it will give the same answer:
print("Length of the calendar dictionary keys is: ",
len(calendar.keys()))
The result is:
Length of the calendar dictionary keys is: 12
Find the length of a dictionary’s values
Similarly, we can first extract the values of the dictionary and then apply len() on that result. Again we will get the same answer:
print("Length of the calendar dictionary values is: ",
len(calendar.values()))
The result is:
Length of the calendar dictionary values is: 12
Finding the length of an empty dictionary
If you have an empty dictionary, the length as expected will be zero.
mydictionary = {}
print("Length of mydictionary is:",len(mydictionary))
The output is:
Length of mydictionary is: 0
Finding the length of a nested dictionary
Let us assume we have a dictionary corresponding to all the meta data about a movie, like so:
harrypotter = {"name": "Harry Potter and the Sorcerer's Stone",
"year released": 2001,
"rating": "PG",
"cast": {
"Harry Potter": "Daniel Radcliffe",
"Hermione Granger": "Emma Watson",
"Baby Harry Potter": "Saunders Triplets",
"Ron Weasley": "Rupert Grint"
}}
print(len(harrypotter))
The output is:
4
The answer is 4 because there are four top-level keys and four top-level values. Note that even though the value for the “cast” key is itself a dictionary (with four keys and four values) the len() function does not flatten this dictionary out and give the result as 7. The total length of the harrypotter dictionary is only 4.
If you would like to flatten the dictionary inside the dictionary and count the total as 3+4, we need to write a function to do so. We should probably also account for the case where there are dictionaries within dictionaries within dictionaries, and so on. Hence, it is good to write a recursive function that drills as deep into the dictionary as necessary.
Here is such a recursive function:
def recursive_length(d):
answer = 0
for x in d.values():
if isinstance(x,dict):
answer += recursive_length(x)
else:
answer += 1
return(answer)
The function recursive_length() takes a dictionary “d” as input, tests, goes through each value of the dictionary, and keeps a running count of values encountered. If the value is itself a dictionary, it calls recursive_length() recursively on that value. Else it adds 1 to the running count and returns the answer.
If you apply it on the harrypotter dictionary like so:
print(recursive_length(harrypotter))
we will get:
7
as intended.
Let us try it on multiple levels of nesting and with multiple instances of nesting in a given dictionary:
harrypotter = {"name": "Harry Potter and the Sorcerer's Stone",
"released": {
"month": "December",
"year": 2001,
},
"rating": "PG",
"cast": {
"Harry Potter": "Daniel Radcliffe",
"Hermione Granger": "Emma Watson",
"Baby Harry Potter": "Saunders Triplets",
"Ron Weasley": "Rupert Grint"
},
"crew": {
"Direction": {
"Main": "Chris Columbus",
"First Asistant": "Chris Carreras"
},
"Writing": {
"Story": "J.K. Rowling",
"Screenplay": "Steve Kloves"
}
}
}
print(recursive_length(harrypotter))
The result is:
12
(You can verify that this is true.) Note that this approach to counting the keys does not count the keys such as “released”, “cast”, “crew”, “Direction”, and “Writing” whose values are dictionaries themselves. If you desire to count these keys as well you need to pass on a counter every time you do the recursion (beginning at zero). See the code below:
def recursive_length(d,sum):
answer = sum
for x in d.values():
if isinstance(x,dict):
answer += recursive_length(x,1)
else:
answer += 1
return(answer)
Note that it takes two arguments, a dictionary and a sum. Everytime a recursive call is made, this sum is set to 1 (to account for the key whose value is itself a dictionary).
When we try it with:
print(recursive_length(harrypotter,0))
we will get the answer we are expecting:
17
In this blogpost, we have learnt how to find the length of a dictionary in Python and how to recursively find the length when there are dictionaries embedded within dictionaries. Enjoy experimenting with the functions introduced here! Learn more about dictionaries in our posts about empty dictionaries in Python, and how to initialize a dictionary in Python.
Once you are comfortable with dictionaries, learn how to increment a value in a Python dictionary, and how to find the first key in a Python dictionary.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.