Last updated: Apr 9, 2024
Reading timeยท10 min
To get multiple values from a dictionary:
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site'] values = [my_dict[key] for key in keys] print(values) # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com'] # ---------------------------------------- # ๐๏ธ using dict.get() values = [my_dict.get(key) for key in keys] print(values) # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com']
We used a list comprehension to iterate over the collection of dictionary keys.
On each iteration, we access the current key and return the corresponding value.
The new list only contains the values of the specified keys.
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site'] values = [my_dict[key] for key in keys] print(values) # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com']
if
statement to check if the specified keys existIf you use bracket notation to access a key that doesn't exist in the dictionary
a KeyError
exception is raised.
You can use an if
statement to check if the key is present in the dictionary
before accessing it.
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site', 'another', 'example'] values = [my_dict[key] for key in keys if key in my_dict] print(values) # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com']
We only use bracket notation to access the key if it exists in the dictionary.
KeyError
exception even if some of the keys don't exist.dict.get()
to check if the specified keys existThere is also a dict.get()
method. The method
returns None for non-existent keys by default.
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site', 'another'] values = [my_dict.get(key) for key in keys] # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com', None] print(values)
The dict.get() method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.
The method takes the following 2 parameters:
Name | Description |
---|---|
key | The key for which to return the value |
default | The default value to be returned if the provided key is not present in the dictionary (optional) |
default
parameter is not provided, it defaults to None
, so the get()
method never raises a KeyError
.If you need to specify a default value for non-existent keys, pass a second
argument in the call to the dict.get()
method.
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site', 'another'] values = [my_dict.get(key, 'default value') for key in keys] # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com', 'default value'] print(values)
Alternatively, you can use a for loop.
This is a three-step process:
for
loop to iterate over the collection of keys.list.append()
method to append the value of each key to a list.my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site', 'another', 'example'] values = [] for key in keys: if key in my_dict: values.append(my_dict[key]) print(values) # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com']
We used a for
loop to iterate over the collection of keys.
list.append()
method to add its value to a new list.The list.append() method adds an item to the end of the list.
Alternatively, you can use the dict.get()
method to access each key.
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site', 'another', 'example'] values = [] for key in keys: values.append(my_dict.get(key)) print(values) # ๐๏ธ ['Borislav Hadzhiev', 'bobbyhadz.com', None, None]
Make sure to pass a second argument to the dict.get()
method if you need to
specify a default value for non-existent keys.
If you need to add multiple values per key in a dictionary:
a_dict = {} a_dict['site'] = ['bobby', 'hadz', 'com'] print(a_dict) # ๐๏ธ {'site': ['bobby', 'hadz', 'com']} print(a_dict['site']) # ๐๏ธ ['bobby', 'hadz', 'com'] print(a_dict['site'][0]) # ๐๏ธ bobby
We used bracket notation to add the site
key to a dictionary and set the key
to a list
of values.
If you need to add a new value to the specific key, access the key and use the
list.append()
method.
a_dict = {} a_dict['site'] = ['bobby', 'hadz', 'com'] print(a_dict) # ๐๏ธ {'site': ['bobby', 'hadz', 'com']} a_dict['site'].append('abc') print(a_dict) # ๐๏ธ {'site': ['bobby', 'hadz', 'com', 'abc']}
The list.append() method adds an item to the end of the list.
If you need to add multiple values at once to an existing key, use the
list.extend()
method.
a_dict = {} a_dict['site'] = ['bobby', 'hadz', 'com'] print(a_dict) # ๐๏ธ {'site': ['bobby', 'hadz', 'com']} a_dict['site'].extend(['a', 'b', 'c']) print(a_dict) # ๐๏ธ {'site': ['bobby', 'hadz', 'com', 'a', 'b', 'c']}
The list.extend method takes an iterable and extends the list by appending all of the items from the iterable.
Alternatively, you can use the dict.setdefault()
method.
dict.setdefault()
This is a two-step process:
dict.setdefault()
method to set the default value of the key to a
list.list.extend()
method to add multiple values to the key.a_dict = {} a_dict.setdefault('site', []) a_dict['site'].append('bobby') a_dict['site'].extend(['hadz', 'com']) print(a_dict) # ๐๏ธ {'site': ['bobby', 'hadz', 'com']}
The setdefault() method takes a key and a default value as arguments.
If the key is in the dictionary, the method returns its value.
for
loopIf you have multiple keys that you want to initialize to an empty list (or any
other value), you can use a for
loop.
a_dict = {} keys = ['site_a', 'site_b', 'site_c'] for key in keys: a_dict.setdefault(key, []) # ๐๏ธ {'site_a': [], 'site_b': [], 'site_c': []} print(a_dict) a_dict['site_a'].append('bobby') a_dict['site_a'].extend(['hadz', 'com']) # ๐๏ธ {'site_a': ['bobby', 'hadz', 'com'], 'site_b': [], 'site_c': []} print(a_dict)
We used a for
loop to iterate over a list of keys.
dict.setdefault
method to set an empty list as the default value for the current key.The setdefault
method is mainly used when you have an empty dictionary and
know the names of all keys the dictionary will store.
If you don't know the names of the keys in advance, use the defaultdict
class
instead.
defaultdict
This is a two-step process:
defaultdict
class to set a list as the default value for the
dictionary's keys.list.extend()
method.from collections import defaultdict a_dict = defaultdict(list) a_dict['site'].append('bobby') a_dict['site'].extend(['hadz', 'com']) # ๐๏ธ defaultdict(<class 'list'>, {'site': ['bobby', 'hadz', 'com']}) print(a_dict) print(a_dict['site']) # ๐๏ธ ['bobby', 'hadz', 'com'] print(a_dict['site'][0]) # ๐๏ธ bobby
We passed the list() class to the
defaultdict
class to use a list as the default value for keys that don't exist
in the dictionary.
The first argument the defaultdict class takes is a function that returns the default value for all keys.
defaultdict
class returns the specified default value when a non-existent key is accessed.from collections import defaultdict a_dict = defaultdict(list) print(a_dict['key']) # ๐๏ธ [] print(a_dict['another_key']) # ๐๏ธ []
If you access a non-existent key in a regular dictionary, you'd get a KeyError
exception.
If you have to set a list as the default value for an existing dictionary, pass
a second argument to the defaultdict()
class.
from collections import defaultdict a_dict = {'name': 'bobby'} a_dict = defaultdict(list, a_dict) a_dict['site'].append('bobby') # ๐๏ธ defaultdict(<class 'list'>, {'name': 'bobby', 'site': ['bobby']}) print(a_dict)
The second argument the defaultdict
class takes is optional and can be a
dictionary or a list of key-value pairs.
Trying to access any key that doesn't exist in the dictionary now returns a list.
You can directly use list methods on non-existent keys.
I've also written an article on how to filter a list of dictionaries.
To find a dictionary's items whose key matches a substring:
my_dict = { 'First_Name': 'Bobby', 'Last_Name': 'Hadz', 'language': 'Python' } partial_key = 'name' matching_values = [ value for key, value in my_dict.items() if partial_key.lower() in key.lower() ] print(matching_values) # ๐๏ธ ['Bobby', 'Hadz']
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = { 'First_Names': 'Bobby', 'Last_Names': 'Hadz', 'language': 'Python' } # ๐๏ธ dict_items([('First_Name', 'Bobby'), # ('Last_Name', 'Hadz'), ('language', 'Python')]) print(my_dict.items())
We used a list comprehension to iterate over the dictionary's items.
On each iteration, we check if the substring is contained in the current key.
my_dict = { 'First_Name': 'Bobby', 'Last_Name': 'Hadz', 'language': 'Python' } partial_key = 'name' matching_values = [ value for key, value in my_dict.items() if partial_key.lower() in key.lower() ] print(matching_values) # ๐๏ธ ['Bobby', 'Hadz']
If the condition is met, we return the corresponding value.
The new list only contains the values of the matching keys.
str.lower()
method to convert the substring and the key to lowercase to test for membership ignoring the case.Converting both strings to lowercase or uppercase allows for a case-insensitive string comparison.
The in operator tests
for membership. For example, x in s
evaluates to True
if x
is a member of
s
, otherwise it evaluates to False
.
If you need to get a dictionary containing the matching items, use a dict comprehension.
my_dict = { 'First_Name': 'Bobby', 'Last_Name': 'Hadz', 'language': 'Python' } partial_key = 'name' matching_items = { key: value for key, value in my_dict.items() if partial_key.lower() in key.lower() } # ๐๏ธ {'First_Name': 'Bobby', 'Last_Names': 'Hadz'} print(matching_items)
Dict comprehensions are very similar to list comprehensions.
They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.
The new dictionary only contains the items whose key matches the specified substring.
If you only need the first dictionary value whose key contains the given string,
use the next()
function.
my_dict = { 'First_name': 'Bobby', 'Last_name': 'Hadz', 'language': 'Python' } partial_key = 'name' first_match = next( (value for key, value in my_dict.items() if partial_key.lower() in key.lower()), None ) print(first_match) # ๐๏ธ Bobby
When we pass the iterator to the next()
function, the next item in the stream
is returned.
We specified a default value of None
which is used if none of the keys in the
dictionary contains the given string.
You can also use the filter()
function to find the dictionary items whose key
match a given substring.
my_dict = { 'First_Name': 'Bobby', 'Last_Name': 'Hadz', 'language': 'Python' } partial_key = 'name' matching_values = dict( filter( lambda item: partial_key.lower() in item[0].lower(), my_dict.items() ) ) # ๐๏ธ {'First_Name': 'Bobby', 'Last_Name': 'Hadz'} print(matching_values)
The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
The lambda function we passed to filter
gets called with each key-value pair
of the dictionary.
The function checks if the substring is contained in the key and returns the matching key-value pair if the condition is met.
To access dictionary values with a key starting with a given string:
my_dict = { 'name_first': 'Bobby', 'name_last': 'Hadz', 'language': 'Python' } key_prefix = 'name' matching_values = [ value for key, value in my_dict.items() if key.lower().startswith(key_prefix.lower()) ] print(matching_values) # ๐๏ธ ['Bobby', 'Hadz']
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = { 'name_first': 'Bobby', 'name_last': 'Hadz', 'language': 'Python' } # ๐๏ธ dict_items([('name_first', 'Bobby'), ('name_last', 'Hadz'), ('language', 'Python')]) print(my_dict.items())
We used a list comprehension to iterate over the dictionary's items.
On each iteration, we use the str.startswith()
method to check if the current
key starts with the given string.
my_dict = { 'name_first': 'Bobby', 'name_last': 'Hadz', 'language': 'Python' } key_prefix = 'name' matching_values = [ value for key, value in my_dict.items() if key.lower().startswith(key_prefix.lower()) ] print(matching_values) # ๐๏ธ ['Bobby', 'Hadz']
The
str.startswith
method returns True
if the string starts with the provided prefix, otherwise
the method returns False
.
str.lower()
method to perform a case-insensitive comparison.If you only need to get the first value in the dictionary whose key starts with
the given prefix, use the next()
function.
my_dict = { 'name_first': 'Bobby', 'name_last': 'Hadz', 'language': 'Python' } partial_key = 'name' value = next( (value for key, value in my_dict.items() if key.lower().startswith(partial_key.lower())), None ) print(value) # ๐๏ธ Bobby
When we pass the iterator to the next()
function, the next item in the stream
is returned.
We specified a default value of None
which is used if none of the keys in the
dictionary starts with the given string.
You can learn more about the related topics by checking out the following tutorials: