The length of a dictionary refers to the number of key-value pairs it contains. In this blog post, we will explore different methods to find the length of a dictionary in Python.
Method 1: Using the len() Function
# Method 1: Using the len() Function my_dict = {"name": "John", "age": 30, "city": "New York"} length = len(my_dict) print("The length of the dictionary is:", length)
Output:
The length of the dictionary is: 3
Method 2: Using the len() Function on Keys or Values
# Method 2: Using the len() Function on Keys or Values my_dict = {"name": "John", "age": 30, "city": "New York"} key_length = len(my_dict.keys()) value_length = len(my_dict.values()) print("The length of the keys is:", key_length) print("The length of the values is:", value_length)
Output:
The length of the keys is: 3
The length of the values is: 3