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)
Explanation
- A dictionary
myDictionary
is created with three key-value pairs:"name": "Lini"
,"year": 1989
, and"expertise": "data analytics"
. - The
len()
function is used to find the length of the dictionary, which returns the number of key-value pairs in it. - The result is stored in the variable
length
, which will be3
because there are three items in the dictionary. - The
print()
function is then used to display the message'Length of dictionary is: 3'
.
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)
Explanation
- An empty dictionary
myDictionary
is created. - The
len()
function is used to find the length of the dictionary, which returns the number of key-value pairs in it. - Since the dictionary is empty, the length will be
0
. - The
print()
function is then used to display the message'Length of dictionary is: 0'
.
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.