Get multiple values from a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
10 min

banner

# Table of Contents

  1. Get multiple values from a dictionary in Python
  2. Dictionary with multiple values per Key in Python
  3. Find dictionary items whose key matches Substring in Python
  4. Access dictionary values with Key starting with given String

# Get multiple values from a dictionary in Python

To get multiple values from a dictionary:

  1. Use a list comprehension to iterate over the collection of keys.
  2. Access each key and return the corresponding value.
  3. The new list will contain the values of the specified keys.
main.py
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']

get multiple values from dictionary

The code for this article is available on GitHub

We used a list comprehension to iterate over the collection of dictionary keys.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we access the current key and return the corresponding value.

The new list only contains the values of the specified keys.

main.py
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 an if statement to check if the specified keys exist

If 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.

main.py
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']

using if statement to check if specified keys exist

The code for this article is available on GitHub

We only use bracket notation to access the key if it exists in the dictionary.

This way, we won't get a KeyError exception even if some of the keys don't exist.

# Using dict.get() to check if the specified keys exist

There is also a dict.get() method. The method returns None for non-existent keys by default.

main.py
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)

using dict get to check if specified keys exist

The code for this article is available on GitHub

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:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)
If a value for the 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.

main.py
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.

# Get multiple values from a dictionary using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the collection of keys.
  2. Use the list.append() method to append the value of each key to a list.
  3. The new list will only contain the values of the specified keys.
main.py
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']
The code for this article is available on GitHub

We used a for loop to iterate over the collection of keys.

On each iteration, we check if the key is present in the dictionary and use the 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.

main.py
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.

# Dictionary with multiple values per Key in Python

If you need to add multiple values per key in a dictionary:

  1. Store the values in a list.
  2. Use bracket notation to add the key to the dictionary.
  3. Set the key to the list of values.
main.py
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
The code for this article is available on GitHub

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.

main.py
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.

# Adding multiple values at once to an existing key

If you need to add multiple values at once to an existing key, use the list.extend() method.

main.py
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.

# Dictionary with multiple values per Key using dict.setdefault()

This is a two-step process:

  1. Use the dict.setdefault() method to set the default value of the key to a list.
  2. Use the list.extend() method to add multiple values to the key.
main.py
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 code for this article is available on GitHub

The setdefault() method takes a key and a default value as arguments.

If the key is in the dictionary, the method returns its value.

If the key is not in the dictionary, the method inserts the key with the specified value.

# Dictionary with multiple values per Key using a for loop

If you have multiple keys that you want to initialize to an empty list (or any other value), you can use a for loop.

main.py
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.

On each iteration, we use the 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.

# Dictionary with multiple values per Key using defaultdict

This is a two-step process:

  1. Use the defaultdict class to set a list as the default value for the dictionary's keys.
  2. Directly access any key in the dictionary and add values to it using the list.extend() method.
main.py
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
The code for this article is available on GitHub

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.

The defaultdict class returns the specified default value when a non-existent key is accessed.
main.py
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.

main.py
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.

# Find dictionary items whose key matches Substring in Python

To find a dictionary's items whose key matches a substring:

  1. Use a list comprehension to iterate over the dictionary's items.
  2. Check if the substring is contained in each key.
  3. The new list will only contain the values of the matching keys.
main.py
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']

find dictionary items whose key matches substring

The code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
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.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the substring is contained in the current key.

main.py
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.

We used the 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.

# Getting a dictionary containing the matching key-value pairs

If you need to get a dictionary containing the matching items, use a dict comprehension.

main.py
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)

get dictionary containing matching key value pairs

The code for this article is available on GitHub

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.

# Getting the first dictionary value whose key contains the given string

If you only need the first dictionary value whose key contains the given string, use the next() function.

main.py
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.

# Find dictionary items whose key matches Substring using filter()

You can also use the filter() function to find the dictionary items whose key match a given substring.

main.py
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.

# Access dictionary values with Key starting with given String

To access dictionary values with a key starting with a given string:

  1. Use a list comprehension to iterate over the dictionary's items.
  2. Check if each key starts with the given string.
  3. The new list will only contain the values of the matching keys.
main.py
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 code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
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.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the str.startswith() method to check if the current key starts with the given string.

main.py
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.

We also used the str.lower() method to perform a case-insensitive comparison.

# Getting the first value whose key starts with the given prefix

If you only need to get the first value in the dictionary whose key starts with the given prefix, use the next() function.

main.py
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
The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev