Finding The Length of a Python Dictionary: A Multiprong Approach

python dictionary length

Python Dictionaries allow you to store and organize extensive data collection with a few simple lines of code. As with other data types in Python, you can use the length function to determine the number of entries. However, once you’re dealing with nested dictionaries, you’ll have to tweak your code a little (which is exactly what we’ll do today!).

Before knowing the many ways you can use the length of dictionary python function in your code, we first have to understand what constitutes a Dictionary, what data types these comprehend, and how to structure them.

Dictionaries are one of Python’s Mapping Data Types. They are often referred to as composite data types or associative arrays, given how easy it is to associate keys with a specific value. A dictionary also lets you store data by pairing one item to another in any order you’d like. This process is known as mapping a key to a value, and it’s as simple as associating one item (the key) to another (the value).

What are Python Dictionaries?

Creating a dictionary in Python is just as easy as stating your dictionary’s name, followed by an assignment operator = and opening with curly bracers { } to store your keys and their values. You assign your first key and respective value by typing a colon : between them and a comma , at the end (the comma will separate your first key-value pair from the next one).

dictionary = {
    <key>: <value>,
    <key>: <value>,
    <key>: <value>
}

You can also go for a linear presentation if that’s more to your liking.

dictionary = {<key>: <value>, <key>: <value>, <key>: <value>}

Let’s go for a more practical example. Say you’re organizing your kids’ birthday party and making a list of supplies you’ll need. You can put together a quick and easy list of items (keys) and their respective quantities (values).

Bday_Shopping_List = {
    'cake':1, 
    'ice cream bowl':2, 
    'balloons':40, 
    'chips':5, 
    'napkin packs':4, 
    'Soft Drink Bottles':4, 
    'plastic cups': 30
}

Here’s the same dictionary presented in a linear fashion:

Bday_Shopping_List = {'cake':1, 'ice cream bowl':2, 'balloons':40, 'chips':5, 'napkin packs':4, 'Soft Drink Bottles':4, 'plastic cups': 30}

You can also make a dictionary containing your friend’s phone numbers (similar to your smartphone’s contact list). Granted, if you’d want your dictionary to have the same breadth and specificity as the one on your phone, you’d need to create a more complex version than the ones shown so far, but more on that later.

Friends_Contact_List = {
    'Rachel':13056191239, 
    'Zack':12015678122,
    'Dan':17258729935,
    'Jamie':18556798436
}

As you enter more and more key:values, your dictionaries are bound to get crowded and lengthy. Eventually, keeping track of how many entries your dictionary has becomes a hassle (especially if you’re used to counting them manually). This is when the term length of a dictionary Python comes in clutch!

Python Dictionary Length

By calling in the python dictionary length function, we can quickly determine how many pairs of items (key and key:values) a dictionary contains.

Python dictionary length function is a built-in method that always returns the number of iterable items within a dictionary, its Python syntax being len ( ). The latter means that len ( ) acts as a counter, checking for items with a colon in between separated by a comma. Let’s try using it on our Birthday Shopping List and Friends Contact List.

We’ll call in a print function beneath our dictionary so the terminal can show us its length:

Bday_Shopping_List = {'cake':1, 'ice cream bowl':2, 'balloons':40, 'chips':5, 'napkin packs':4, 'Soft Drink Bottles':4, 'plastic cups': 30}

print(len(Bday_Shopping_List))

# Output:

7
Friends_Contact_List = {
    'Rachel':13056191239, 
    'Zack':12015678122,
    'Dan':17258729935,
    'Jamie':18556798436
}

print(len(Friends_Contact_List))

# Output:

4

We’ll tweak our code to better illustrate our Python dictionary length function output. We’ll assign a variable to our len ( ) function and then use a more detailed print function command.

Bday_Shopping_List = {'cake':1, 'ice cream bowl':2, 'balloons':40, 'chips':5, 'napkin packs':4, 'Soft Drink Bottles':4, 'plastic cups': 30}

length =len(Bday_Shopping_List)

print(f'The Length of this dictionary is {length}')

# Output: 

The Length of this dictionary is 7
Friends_Contact_List = {
    'Rachel':13056191239, 
    'Zack':12015678122,
    'Dan':17258729935,
    'Jamie':18556798436
}
length =len(Friends_Contact_List)

print(f'The Length of this dictionary is {length}')

# Output: 

The Length of this dictionary is 4

The Python dictionary length function counted 7 pairs of items on our Birthday Shopping List dictionary, and 4 in our Friends Contact List. Notice that len ( ) doesn’t count keys and key:values separately: it only counts the number of entries made in your data collection. Still, you could use the Python dictionary length function to count for the specific number of keys, and key:values by targeting each, respectively.

For instance, if we introduce the following variations of the Python dictionary length function in our Friends Contact List len(Friends_Contact_List.keys()) our terminal can specify the number of keys entered in this dictionary:

Friends_Contact_List = {
    'Rachel':13056191239, 
    'Zack':12015678122,
    'Dan':17258729935,
    'Jamie':18556798436
}
print(len(Friends_Contact_List.keys()))

# Output:

4

Likewise, if we target values through the Python dictionary length function by typing len(Friends_Contact_List.values()), we’ll get the terminal to count how many values it contains.

Friends_Contact_List = {
    'Rachel':13056191239, 
    'Zack':12015678122,
    'Dan':17258729935,
    'Jamie':18556798436
}
print(len(Friends_Contact_List.values()))

# Output:

4

You’ll notice that the output for values and keys are the same as when we called our first Python dictionary length function. Since there are 4 pairs of items in our Friends Contact List, it makes sense that we have 4 keys for each of our four key-value pairs in our dictionary.

Len () Function Notes for Keys and Key-Value Pairs

The len ( ) and len ( .keys( ) ) functions come with some initial limitations that you need to be aware of (specifically whenever there are duplicate keys).

  • Duplicate keys are counted as a single key.
  • Duplicate values are counted separately (several keys can have the same value pair).
  • Using the length of dictionary python function to count keys with no assigned values will result in an error.

Length Dictionary Python And Nested Dictionaries

Let’s fantasize and imagine that you’ve just won the lottery and are now getting $100 million (after tax, of course). Naturally, you’d want to spread some love among your besties by wiring them $10,000 each through Cash App. You’ll need to update your Friends Contact List dictionary to include their numbers and Cash App registered emails.

Python dictionaries can do that for you by assigning their keys to an inner dictionary; the latter will work just fine as our previous (and simpler) key:values. Nested dictionaries are pretty handy, as you can pair a singular key to several values (in this case, our friend’s emails and contact numbers).

Let’s expand what each of our names (Keys) can retain in our Friends Contact List so we can store both their email addresses and their contact numbers:

Friends_Contact_List = {
    'Rachel':{ 
        'Phone Number':13056191239,
        'Email':'Rachel2000@gmail.com',
            },
    'Zack':{ 
        'Phone Number':12015678122,
        'Email':'Zackman@gmail.com',
            },
    'Dan':{ 
        'Phone Number':17258729935,
        'Email':'DanielCorrado@gmail.com',
            },
    'Jimmy':{ 
        'Phone Number':18556798436,
        'Email':'JimmyMcGil@gmail.com',
            }
}

Just like we did before, we’ll state the name of a friend (create a key) within our first curly bracers, and as soon as we type our colons to pair them with a value, we add yet another set of curly bracers that include a subset of paired items named Phone Number and Email. This subset of keys will have individual values (phone number and email) assigned to them.

Our code went from this:

'Rachel':13056191239,

To this:

'Rachel':{ 
    'Phone Number':13056191239,
    'Email':'Rachel2000@gmail.com',
        },

What if we want to use the length dictionary Python function to verify how many paired items, keys, and values are present in our dictionary? Let’s run all three length dictionary Python functions at once while adding the length, keys and values variable to our print functions to better illustrate our results.

Friends_Contact_List = {
    'Rachel':{ 
        'Phone Number':13056191239,
        'Email':'Rachel2000@gmail.com',
            },
    'Zack':{ 
        'Phone Number':12015678122,
        'Email':'Zackman@gmail.com',
            },
    'Dan':{ 
        'Phone Number':17258729935,
        'Email':'DanielCorrado@gmail.com',
            },
    'Jimmy':{ 
        'Phone Number':18556798436,
        'Email':'JimmyMcGil@gmail.com',
            }
}
length =len(Friends_Contact_List)
keys= len(Friends_Contact_List.keys())
values= len(Friends_Contact_List.values())

print(f'The Length of this dictionary is {length}')
print(f'The number of keys in this dictionary is {keys}')
print(f'The number of values in this dictionary is {values}')

# Output:

The Length of this dictionary is 4
The number of keys in this dictionary is 4  
The number of values in this dictionary is 4

Hold on a minute: our output is still 4. Why is it not counting the extra entries we added for each friend? As we mentioned before, the length dictionary Python function only counts the number of entries made for each pairing. This means each inner dictionary is counted as a single key:value entry, regardless of the data it contains.

You might be wondering: how can we get a more accurate result? In order to do that, we’ll need to tweak our code a bit. We’ll need to make the length dictionary Python function a bit more specific in our code, so it counts not just the pairings in our first level of curly bracers (main dictionary) but also each of those in our second level curly bracers (the nested dictionary).

Friends_Contact_List = {
    'Rachel':{ 
        'Phone Number':13056191239,
        'Email':'Rachel2000@gmail.com',
            },
    'Zack':{ 
        'Phone Number':12015678122,
        'Email':'Zackman@gmail.com',
            },
    'Dan':{ 
        'Phone Number':17258729935,
        'Email':'DanielCorrado@gmail.com',
            },
    'Jimmy':{ 
        'Phone Number':18556798436,
        'Email':'JimmyMcGil@gmail.com',
            }
}
Length=len(Friends_Contact_List)+len(Friends_Contact_List['Rachel'])+len(Friends_Contact_List['Zack'])+len(Friends_Contact_List['Dan'])+len(Friends_Contact_List['Jimmy'])

print(f'The Length of this dictionary is {length}')

# Output: 

The Length of this dictionary is 12

We’ve adjusted our code to count whatever entries exist inside each of our main dictionary keys (our friend’s names). In our Length variable (the one we used to call our length dictionary Python function), we manually added a specific len ( ) for each of our keys to get an accurate count.

Length=len(Friends_Contact_List)+len(Friends_Contact_List['Rachel'])+len(Friends_Contact_List['Zack'])+len(Friends_Contact_List['Dan'])+len(Friends_Contact_List['Jimmy'])

The latter might have solved our accuracy issues, but it’s not a practical solution for every nested dictionary we’d like to use in the future. Whenever we need to get an accurate len ( ) result for any super extensive nested dictionary, we can use a nifty little function known as the isinstance method.

Python Length of Dictionary Function: The isinstance Method

Recursive functions such as loops are perfect for iterating over every line of our code. The goal here is to count how many inner dictionaries are used as key:values, and add each of them to the built-in Python Length of Dictionary Function’s counter len ( )

But how can our loop distinguish key:values from simple values and nested dictionaries? This is when the isinstance function comes to our aid. The isinstance( ) function returns True if its object is of a specific data type, including mapping data types such as dictionaries. Let’s test it with several data types to see how it works:

Checking if the isinstance function recognizes a string data type (str)

Test = isinstance("Hello", (str))

print(Test)

# Output: 

True

What if we deliberately put a non-string value in the isinstance object when checking for strings? It should return us a False right?

Test = isinstance(22, (str))

print(Test)

# Output: 

False

Awesome, let’s have the isinstance function try for floats in a similar manner:

Test = isinstance(1.2, (float))

print(Test)

# Output: 

True

Great, now lets see if the isinstance function recognizes dictionary data types:

Dictionary = {"key":20}
Test = isinstance(Dictionary, (dict))

print(Test)

# Output: 

True

How cool! Now we know for a fact that this function can be of use for checking if a dictionary parameter (in this case our key:values) is a dict (a dictionary data type). All that it’s left for us to do is to write a for loop that uses the isinstance function to check if our dictionary values are of dict data type and order it to add a count to len ( ) whenever that’s the case.

Friends_Contact_List = {
    'Rachel':{ 
        'Phone Number':13056191239,
        'Email':'Rachel2000@gmail.com',
            },
    'Zack':{ 
        'Phone Number':12015678122,
        'Email':'Zackman@gmail.com',
            },
    'Dan':{ 
        'Phone Number':17258729935,
        'Email':'DanielCorrado@gmail.com',
            },
    'Jimmy':{ 
        'Phone Number':18556798436,
        'Email':'JimmyMcGil@gmail.com',
            }
}
length=len(Friends_Contact_List)
for i in Friends_Contact_List.values():
        if isinstance(i, dict):
            length += len(i)

print(f'The Length of this dictionary is {length}')

# Output: 

The Length of this dictionary is 12

Lets go a bit in detail with how our for loop is checking for dict data types and adding then to our Python Length of Dictionary Function’s counter len ( )

length=len(Friends_Contact_List)
for i in Friends_Contact_List.values():
        if isinstance(i, dict):
            length += len(i)

print(f'The Length of this dictionary is {length}')

First, we establish length as a variable for our len ( ) function:

length=len(Friends_Contact_List)

Since our dictionary is using inner dictionaries (nested dictionaries) as key:values, lets write a for loop that will iterate on our dictionary’s values using the isinstance function:

for i in Friends_Contact_List.values():

Our condition states that if the isinstance function detects a dict data type, then the len( ) counter must increase by 1.

if isinstance(i, dict):
    length += len(i)

And there you have it: you can use this code as the baseline for Programming a Python Length of Dictionary Function with The isinstance Method to automatically get an accurate len ( ) return for your nested dictionaries!

Closing Words

The Python dictionary is a powerful data structure that features key-value pairs indexed by a non-mutable data type. The len ( ) function will always return an accurate count of your dictionary’s entries (assuming you’re not using nested dictionaries to organize your data).

If your code features nested dictionaries, you’ll have to adjust your len ( ) function to get an accurate entry count. Using a for loop with an isinstance function to check whether the value of a key is a dictionary is a pretty efficient way to detect and count those subsets of key-value pairs.

If any key or key:values parameter is a dictionary data type dict, the isisnstance method will detect it, and your loop will add it to the len ( ) counter every time. As with many Python-related things, there are many ways to solve a specific problem, so we encourage you to play a bit with mapping data types and the len ( ) function, as both can prove super helpful when handling extensive data collections in your code!

Jesus Aveledo
Design and marketing professional with 5+ years of website development experience. Currently discovering the power of Python in synthesizing content, ideas, and resources for my clients