Master How to Determine the Number of Key-Value Pairs in a Dictionary: 5 Examples
You can find out how many key-value pairs are in a dictionary by using the len()
function. Here are five examples showing how to do this:
- Using
len()
function:
my_dict = {'a': 1, 'b': 2, 'c': 3}
num_pairs = len(my_dict)
print("Number of key-value pairs:", num_pairs) # Output: 3
- Using an empty dictionary:
empty_dict = {}
num_pairs = len(empty_dict)
print("Number of key-value pairs:", num_pairs) # Output: 0
- Using a dictionary comprehension:
keys = ['apple', 'banana', 'orange']
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
num_pairs = len(my_dict)
print("Number of key-value pairs:", num_pairs) # Output: 3
- Using a dictionary with duplicate keys:
duplicate_keys_dict = {'a': 1, 'b': 2, 'a': 3}
num_pairs = len(duplicate_keys_dict)
print("Number of key-value pairs:", num_pairs) # Output: 2 (Counting unique keys)
- Using a nested dictionary:
nested_dict = {'a': {'x': 1, 'y': 2}, 'b': {'x': 3, 'y': 4}}
num_pairs = len(nested_dict)
print("Number of key-value pairs:", num_pairs) # Output: 2 (Counting top-level keys)