In this tutorial, we are going to learn how to find the length of a map in Python.
Mapping represents the connection between two data sets or a relation between the elements of two data sets.
Python includes several mapping types and the main one is the dictionary. Determining the length of a map is easy – it’s the same as finding the length of a dictionary.
Step 1: Creating a Dictionary
Before finding the length, we have to establish a dictionary. In Python, a dictionary is created with curly brackets {}. Here is an example:
1 2 3 4 5 |
my_dict = { "Fruit": "Apple", "Color": "Red", "Size": "Medium" } |
Step 2: Using the len() Function
The built-in Python function len() returns the number of items in an object. When the object is a dictionary, len() returns the number of key-value pairs. Here is how you can apply it:
1 |
print("Length : %d" % len (my_dict)) |
This should return:
Length : 3
Step 3: Checking for Empty dictionaries
If a dictionary is empty, the len() function will return 0:
1 2 |
empty_dict = {} print("Length : %d" % len (empty_dict)) |
This should return:
Length : 0
Code:
1 2 3 4 5 6 7 8 9 10 |
my_dict = { "Fruit": "Apple", "Color": "Red", "Size": "Medium" } print("Length : %d" % len (my_dict)) empty_dict = {} print("Length : %d" % len (empty_dict)) |
Conclusion:
Now you know how to count the number of mappings in a dictionary. The trick lies in the built-in Python function len(), which counts the number of key-value pairs. It’s important to remember that len() will return 0 if there are no items in the dictionary. Keep practicing and enhancing your Python skills!