How to find Length of Dictionary in Python?
Dictionary Length
To get the length of a dictionary or number of key:value pairs in a dictionary, you can use Python builtin function len().
Syntax of len() for Dictionary
The syntax of length function with Python dictionary is given below.
len(myDictionary)
len() returns an integer representing the number of key:value pairs in the dictionary.
Examples
1. Get the length of given dictionary
In the following example, we will initialize a Python Dictionary with some key:value pairs and try to find out the length of this Dictionary using len().
Python Program
myDictionary = {
"name": "Lini",
"year": 1989,
"expertise": "data analytics"}
length = len(myDictionary)
print('Length of dictionary is:', length)
Output
Length of dictionary is: 3
2. Get the length of an empty dictionary
In the following example, we will initialize an empty Python Dictionary and try to find out the length of this Dictionary using len(). The result of course should be returned as zero.
Python Program
myDictionary = {}
length = len(myDictionary)
print('Length of dictionary is:', length)
Output
Length of dictionary is: 0
The result is trivial.
Summary
In this tutorial of Python Examples, we learned how to find length of Python Dictionary using len() with the help of well detailed examples.