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 find keys based on their values, refer to the following article.
You can retrieve all the values from a dictionary as a list by applying the list()
function to its 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'
Using a non-existent key is acceptable when adding 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 the in
keyword to check whether a 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 provide a default value as the second argument, which will be returned if the key is not found.
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'}