Borislav Hadzhiev
Tue Jun 14 2022·2 min read
Photo by Fuu J
Use the len()
function to get the length of a dictionary, e.g.
result = len(my_dict)
. The len()
function can be passed a collection such as
a dictionary and will return the number of key-value pairs in the dictionary.
my_dict = {'name': 'Alice', 'age': 30, 'tasks': ['dev', 'test']} # 👇️ get length of dict result_1 = len(my_dict) print(result_1) # 👉️ 3 # 👇️ get length of a value in the dictionary result_2 = len(my_dict['tasks']) print(result_2) # 👉️ 2
The len() function returns the length (the number of items) of an object.
The first example shows how to get the number of key-value pairs in the dictionary.
If you need to get the length of a value in the dictionary, access the
corresponding key and pass the result to the len()
function.
my_dict = {'name': 'Alice', 'age': 30, 'tasks': ['dev', 'test']} # 👇️ get length of a value in the dictionary result_2 = len(my_dict['tasks']) print(result_2) # 👉️ 2
You can also create a new dictionary that maps the specific keys to the length of their values.
my_dict = {'name': 'Alice', 'tasks': ['dev', 'test']} len_values = {key: len((value)) for key, value in my_dict.items()} print(len_values) # 👉️ {'name': 5, 'tasks': 2} print(len_values['tasks']) # 👉️ 2
Note that this approach only works if all values in the dictionary can be passed
to the len()
function.
You can also use the len()
function to check if a dictionary is empty.
my_dict = {} if len(my_dict) == 0: # 👇️ this runs print('dict is empty') else: print('dict is not empty')
If a dictionary has a length of 0
, then it's empty.
You might also see examples online that check whether the dictionary is truthy (to check if it contains at least 1 key-value pair), which is more implicit.
my_dict = {} if my_dict: print('dict is NOT empty') else: # 👇️ this runs print('dict is empty')
All values that are not truthy are considered falsy. The falsy values in Python are:
None
and False
.0
(zero) of any numeric type""
(empty string), ()
(empty tuple), []
(empty list), {}
(empty dictionary), set()
(empty set), range(0)
(empty
range).Notice that an empty dictionary is a falsy value, so if the dict
is empty, the
else
block is ran.
If you need to check if the dictionary is empty using this approach, you would
negate the condition with not
.
my_dict = {} if not my_dict: # 👇️ this runs print('dict is empty') else: print('dict is NOT empty')