Find Length of Dictionary in Python with Examples

In this article, we will learn different ways to find the length of a dictionary and its values in python.

Find length of dictionary

We can find the length of a dictionary using the in-built len() function in python. It returns the number of keys in the dictionary.

The length of a dictionary means the size of the memory it takes. So we can say, we can check the size of a dictionary using the len() function.

For example, let’s say we have a dictionary with three keys.

person_dict = {
    'name':'John',
    'occupation':'Developer',
    'City':'NY'
}

len_of_dict = len(person_dict)

print(len_of_dict)

Output:

3

So, the length of the given dictionary (person_dict) is 3.

Find length of dictionary values

We can also find the length of the values in a dictionary using the len() function too.

Let’s see an example to find the length of a single dictionary value in python.

For Example:

person = {
    'name':'John',
    'lang': ['English','Spanish','Greek']
}

Here, we have a person dictionary with a lang key whose values are in the list. So to find out the length of the value associated with lang, we will write

person = {
    'name':'John',
    'lang': ['English','Spanish','Greek']
}

len_of_dict = len(person['lang'])

print('Length of single value: ',len_of_dict)

Output:

Length of single value:  3

Here, we have access to the value of a given key using the expression dict[key]. And then passed it to the len() function to get the size of the value.

Now if we want to find the length of all the values in a python dictionary then we can use the sum() function along with the len() function.

For example, let’s say we have a dictionary will two keys.

person = {
    'name':{
        'firstName': 'John',
        'lastName':'Wick'
    },
    'lang': ['English','Spanish','Greek']
}

So to find the length of the values we can use the person.values() method. And then calculate the length of each key’s value and add them together as the final output.

person = {
    'name':{
        'firstName': 'John',
        'lastName':'Wick'
    },
    'lang': ['English','Spanish','Greek']
}

total = 0
for v in person.values(): 
    total +=len(v)

print('length of all values:', total)

Output:

length of all values: 5

The person.values() method returns the values of the keys. So, we can just loop over it and get the length of each value using len(v).

We can also use the dictionary comprehension statement to write the above code in short syntax.

Example:

person = {
    'name':{
        'firstName': 'John',
        'lastName':'Wick'
    },
    'lang': ['English','Spanish','Greek']
}

total_len = sum(len(v) for k, v in person.items())

print('length of all values:', total_len)

Output:

length of all values: 5

Here we have used dictionary comprehension to loop through the values and then used the sum() function to add the length of each value.

Note:

If the value of a key in a dictionary is a string, then the length of the value will be the number of characters in the string. For example

d = {'name':'Johnny'}

len_of_val = len(d['name'])

print(len_of_val) # 6

Find length of nested dictionary in python

Let’s say we have a nested dictionary as shown below.

person = {
    'name':{
        'firstName': 'John',
        'lastName':'Wick'
    },
    'address':{
        'city': 'NY',
        'pin': 9876
    },
    'phone': 55523235,
    'occupation': 'Developer'
}

Here, we have values which are dictionary, numbers, and string.

So to find the total length of the nested dictionary values we have to use the isinstance() function

The isinstance() function takes in two parameters: the object and data type of the object.

isinstance(object, type)

If the object and the data-type match, it returns True, otherwise False.

Using this we can count all the key’s values of the nested dictionary.

Example:

person = {
    'name':{
        'firstName': 'John',
        'lastName':'Wick'
    },
    'address':{
        'city': 'NY',
        'pin': 9876
    },
    'phone': 55523235,
    'occupation': 'Developer',
}

total = 0
for v in person.values():
    if(isinstance(v, dict)):
        total += len(v)
    else:
        total+=1

print('length of all vlaues:', total)

Output:

length of all vlaues: 6

Here, we have looped through the values using the for loop, and then using if statement we checked, if the value is a dictionary or not.

If the value is a dictionary then we calculate the length of the elements using len() function and add the number to the total variable. If the value is not a dict type then we just add 1 to the total variable.

Once done, we print out the total result in the terminal.

Conclusion:

So, these are the ways we can find the size of a dictionary and count the dictionary elements value of a nested dictionary in python.


Other Articles You’ll Also Like:

Sort List or Dictionary by two keys in Python

Save Python dict as JSON: Convert Dictionary to JSON

Scroll to Top