The dictionary size is often termed as length, which indicates the total space occupied in memory by the elements of the dictionary.
So, to find the size of a Python dictionary, users have to find the number of elements in that dictionary, and it is possible by using different methods in Python. This Python article will give an out-and-out idea of how to get the size of a dictionary.
What is a Python Dictionary?
The Python data structures that hold key-value paired data are called dictionaries. Users write the elements or insert the data as a series of key-value pairs inside braces "{ }." A dictionary stores non-duplicate elements in an orderly manner and is mutable, i.e., users can change the values without altering the identity.
Get Size of Dictionary
Syntax:
dictionary = {1: 'A', 2: 'B', 3: 'C'}
How to get the size of a dictionary in Python?
Several methods in Python can help get the size of the Python dictionary. The following is the list of these methods that get the length or size of the specified dictionary:
Method 1: Using len() method
The Python len() method returns the total number of elements in the dictionary and is a built-in method of Python. The method returns an integer value that provides the size of the dictionary.
Syntax:
len(Dict)
Example 1:
Code Snippet:
d = {1: "A", 2: "B", 3: "C", 4: "D"}
print("The dictionary is:", d)
print("Getting the size the dictionary:", len(d))
Output:
Explanation:
As we can see, we have initialized a dictionary with four key-value pairs and used the len() method. The method returns four as the length of the dictionary.
Method 2: Using the getsizeof() function
The getsizeof() method returns the size of the Python dictionary in bytes. It determines how much memory a dictionary occupies. Users can use this function from the sys module, and it is mainly useful when users require code that needs to be performant or needs regular monitoring.
The code sample is as follows:
import sys
d = {1: "A", 2: "B", 3: "C", 4: "D"}
print("Getting the length of the dictionary in {} bytes".format(sys.getsizeof(d)))
Output:
Explanation:
The getsizeof() function returned the size of the dictionary in bytes. The required size is 232 bytes.
Method 3: Using the sum() function
The sum() function is a built-in function in Python that efficiently sum up a list of elements in the dictionary.
Code Snippet:
d = {'Emp_name': 'Abhishek', 'Age': 28, 'Profession': 'Engineer'}
l = sum(1 for key in d)
print("The length of the dictionary is:", l)
Output:
Explanation:
In this example, we created a generator that creates a sequence of 1's, corresponding to the keys in the dictionary. Then we used the sum() function that counts these 1's and returns the length of the dictionary.
Getting the size of nested dictionaries in Python
In Python, a nested dictionary is a dictionary that resides within another parent dictionary. In other words, nested dictionaries inside a dictionary create multiple levels of key-value pairs.
Users can easily simplify complex structures such as JSON responses from APIs using these nested dictionaries.
For instance,
"Emp_name": "A"
"Age": 27
"Profession": "Engineer"
"Address":
"Street": "000 XY Colony"
"City": "Mumbai"
"Country": "India"
Code Snippet:
d = {
"Emp_name": "A", "Age": 27, "Company": "XYZ", "Profession": "Engineer",
"Address": {
"Street": "000 XY Colony",
"City": "Mumbai",
"Country": "India",
}
}
print("The size of the dictionary using len() method:", len(d))
print("The size of the dictionary by keys() :", len(d.keys()))
print("The size of the dictionary by values():", len(d.values()))
Output:
Explanation:
In the above code, we used the len() method to get the size of both the parent and the nested dictionary in Python. In the output, we got only five as the dictionary length though the size is seven.
It is because the len() method considers the nested dictionary as a single element with one of the keys and values.
But users can solve this problem by adding the length of the inner dictionary to the outer one explicitly. Here, is an example of the solved program to get the overall dictionary size:
d = {
"Emp_name": "A", "Age": 27, "Company": "XYZ", "Profession": "Engineer",
"Address": {
"Street": "000 XY Colony",
"City": "Mumbai",
"Country": "India",
}
}
l = len(d)+len(d['Address'])
print("The length of the nested dictionary is:", l)
Output:
Explanation:
In the solved program, we used the same len() method with two inner dictionaries. Then, we explicitly added the length of the nested dictionaries every time we want to find the total size of the dictionary.
Doing so, the method length of the overall dictionary gets stored in a variable (here, "l"). But, it is not an optimized way to get the length.
Example 1: Get length using for-loop and len() method
Users can also get the size of the dictionary dynamically. They simply loop their dictionary and get the size of the dictionary. It is useful in the situation when users want to get the length having multiple dictionaries whose values are again dictionaries, i.e., nested dictionaries.
If the values are nested dictionaries, then users need to check the type of the value of each key. Then users can use the len() method with for loop on the values and insert the value to the length of the parent dictionary.
Code Snippet:
d = {
"Emp_name": {
"first_name": 'ABC',
"Last_name": 'XYZ'
},
"Age": 27, "Company": "Sample", "Profession": "Engineer",
"Address": {
"Street": "000 XY Colony",
"City": "Mumbai",
"Country": "India",
}
}
l = len(d)
for i in d.values():
if isinstance(i, dict):
l += len(i)
print("The size of the dictionary is", l)
Output:
Explanation:
We have easily solved the problem using the two methods isinstance() and len() method. The len() method will calculate the number of elements in the dictionary, and the isinstance() method returns True if a specific object is of a specific type.
The for loop will iterate through all the key-value pairs of the dictionary by checking whether it is an element of the dictionary. In this way, we get the total size of the Python dictionary.
Example 2: Getting the size of the dictionary using recursion:
Code Snippet:
d = {
"Emp_name": {
"first_name": 'ABC',
"Last_name": 'XYZ'
},
"Age": 27, "Company": "Sample", "Profession": "Engineer",
"Address": {
"Street": "000 XY Colony",
"City": "Mumbai",
"Country": "India",
}
}
def nested_dict(d):
l = len(d)
for key, value in d.items():
if isinstance(value, dict):
l += nested_dict(value)
return l
print("The size of the dictionary is:", nested_dict(d))
Output:
Explanation:
In this example, we used the recursive function nested_dict() to count the number of elements to get the dictionary size. Then the function iterates on the keys of dictionaries, and when it encounters a nested dictionary as a value, it recuses on that dictionary.
Conclusion
We hope this Python article has given a crisp idea of how to get the size of a dictionary using different approaches. Users can use any approach based on their requirements and efficiently get the length or size of the specified dictionary counting all the key-value pairs.