Get a value from a dictionary by key in Python
This article explains how to get a value from a dictionary (dict
) by key in Python.
If you want to extract keys based on their values, see the following article.
You can get all the values in a dictionary as a list using the list()
function with the values()
method.
d = {'key1': 1, 'key2': 2, 'key3': 3}
print(list(d.values()))
# [1, 2, 3]
Get a value from a dictionary with dict[key]
(KeyError
for non-existent keys)
In Python, you can get a value from a dictionary by specifying the key like dict[key]
.
d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
print(d['key1'])
# val1
In this case, KeyError
is raised if the key does not exist.
# print(d['key4'])
# KeyError: 'key4'
Specifying a non-existent key is not a problem if you want to add a new element to the dictionary.
d['key4'] = 'val4'
print(d)
# {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}
For more information about adding items to the dictionary, see the following article.
Use in
to check if the key exists in the dictionary.
Use dict.get()
to get the default value for non-existent keys
You can use the get()
method of a dictionary (dict
) to get a value without an error. If the key does not exist, a default value can be returned.
Specify the key as the first argument. If the key exists, the corresponding value is returned. Otherwise, None
is returned.
d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
print(d.get('key1'))
# val1
print(d.get('key4'))
# None
You can specify the default value in the second argument, to be returned when the key does not exist.
print(d.get('key4', 'NO KEY'))
# NO KEY
print(d.get('key4', 100))
# 100
The original dictionary remains unchanged.
print(d)
# {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}