Skip to main content

How to get the number of key-value pairs in a dictionary in Python

How to get the number of key-value pairs in a dictionary in Python.

Here's a step-by-step tutorial on how to get the number of key-value pairs in a dictionary in Python.

Step 1: Create a dictionary

To begin, you need to create a dictionary. A dictionary in Python is a collection of key-value pairs enclosed in curly braces {}. Each key-value pair is separated by a colon :. Here's an example of creating a dictionary:

my_dict = {"apple": 2, "banana": 3, "orange": 5}

In this example, we have a dictionary with three key-value pairs: "apple" with a value of 2, "banana" with a value of 3, and "orange" with a value of 5.

Step 2: Using the len() function

To get the number of key-value pairs in a dictionary, we can use the built-in len() function in Python. The len() function returns the number of elements in a container, such as a dictionary. Here's an example of using the len() function to count the number of key-value pairs in a dictionary:

my_dict = {"apple": 2, "banana": 3, "orange": 5}
count = len(my_dict)
print("Number of key-value pairs:", count)

Output:

Number of key-value pairs: 3

In this example, the len() function is applied to the my_dict dictionary, and the result is stored in the count variable. Finally, we print the value of count, which gives the number of key-value pairs in the dictionary.

Step 3: Accessing the dictionary's keys or values

If you want to get the number of keys or values separately, Python provides methods for that as well.

To get the number of keys in a dictionary, you can use the len() function on the keys() method of the dictionary. Here's an example:

my_dict = {"apple": 2, "banana": 3, "orange": 5}
key_count = len(my_dict.keys())
print("Number of keys:", key_count)

Output:

Number of keys: 3

In this example, we use the keys() method to get a list of all the keys in the dictionary, and then apply the len() function to count the number of keys.

Similarly, to get the number of values in a dictionary, you can use the len() function on the values() method of the dictionary. Here's an example:

my_dict = {"apple": 2, "banana": 3, "orange": 5}
value_count = len(my_dict.values())
print("Number of values:", value_count)

Output:

Number of values: 3

In this example, we use the values() method to get a list of all the values in the dictionary, and then apply the len() function to count the number of values.

That's it! You now know how to get the number of key-value pairs, keys, and values in a dictionary using Python.