Skip to main content

How to Access and Filter Dictionary Values in Python

This guide explores different techniques for accessing and filtering values within Python dictionaries. We'll cover:

  • Getting multiple values by providing a list of keys.
  • Handling cases where keys might not exist.
  • Creating dictionaries with multiple values per key.
  • Filtering dictionaries based on key substrings.

Getting Multiple Values by Keys

To retrieve multiple values from a dictionary, given a list of keys, use a list comprehension:

my_dict = {
'name': 'Tom Nolan',
'site': 'tutorialreference.com',
'id': 1,
'topic': 'Python'
}

keys = ['name', 'site']
values = [my_dict[key] for key in keys]
print(values) # Output: ['Tom Nolan', 'tutorialreference.com']
  • The list comprehension [my_dict[key] for key in keys] goes through the list of keys and retrieves the corresponding value from the dictionary.

Handling Missing Keys with if

To avoid KeyError exceptions if a key might not exist, use an if condition within the list comprehension:

keys = ['name', 'site', 'another', 'example']
values = [my_dict[key] for key in keys if key in my_dict]
print(values) # Output: ['Tom Nolan', 'tutorialreference.com']
  • The if key in my_dict: check makes sure the key exists in the dictionary before accessing its value, preventing KeyError.

Using dict.get() for Default Values

An even better approach is to use the dict.get() method, which allows you to specify a default value for missing keys:

keys = ['name', 'site', 'another']
values = [my_dict.get(key, 'default value') for key in keys]
print(values) # Output: ['Tom Nolan', 'tutorialreference.com', 'default value']
  • The .get() method will try to access each key, and if the key is not in the dictionary it will return the default value (or None if no default value is specified).
  • This approach prevents your code from crashing if the key is missing.

Creating Dictionaries with Multiple Values per Key

To store multiple values for a single key, use lists as the values in your dictionary:

a_dict = {}
a_dict['site'] = ['tutorial', 'reference', 'com']

print(a_dict) # Output: {'site': ['tutorial', 'reference', 'com']}

a_dict['site'].append('abc')
print(a_dict) # Output: {'site': ['tutorial', 'reference', 'com', 'abc']}

a_dict['site'].extend(['def', 'ghi'])
print(a_dict) # Output: {'site': ['tutorial', 'reference', 'com', 'abc', 'def', 'ghi']}

  • To add multiple elements, use the extend() method.

Initializing with Lists

When creating the dictionary, initialize each key with an empty list:

a_dict = {}
keys = ['site_a', 'site_b', 'site_c']
for key in keys:
a_dict.setdefault(key, []) # Set default list if key is not present
print(a_dict) # Output: {'site_a': [], 'site_b': [], 'site_c': []}

Using dict.setdefault()

Alternatively, use the dictionary's setdefault() method:

a_dict = {}
a_dict.setdefault('site', []).extend(['tutorial', 'reference', 'com'])
print(a_dict) # Output: {'site': ['tutorial', 'reference', 'com']}
  • The .setdefault() method will set a value of an empty list to the key, if the key does not exist. If it does exist, it will simply return the existing value.

Using collections.defaultdict

The defaultdict will automatically initialize empty lists if the key has not been set.

from collections import defaultdict

a_dict = defaultdict(list) # Set the default value to be an empty list.
a_dict['site'].append('tutorial')
a_dict['site'].extend(['reference', 'com'])
print(a_dict) # Output: defaultdict(<class 'list'>, {'site': ['tutorial', 'reference', 'com']})

Filtering Dictionary Items by Key Substring

To find dictionary items where the key contains a specific substring:

Getting All Matching Values

my_dict = {
'First_Name': 'tutorial',
'Last_Name': 'Nolan',
'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) # Output: ['Tom', 'Nolan']

Getting a Dictionary of Matching Items

my_dict = {
'First_Name': 'tutorial',
'Last_Name': 'Nolan',
'language': 'Python'
}

partial_key = 'name'
matching_items = {
key: value for key, value in my_dict.items()
if partial_key.lower() in key.lower()
}
print(matching_items)
# Output: {'First_Name': 'Tom', 'Last_Name': 'Nolan'}
  • The dictionary comprehension filters the elements of the dictionary based on the specified criteria.

Getting the First Matching Value

To get only the first matching value:

my_dict = {
'First_name': 'Tom',
'Last_name': 'Nolan',
'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) # Output: Tom
  • This is the fastest way to get a single value.
  • The generator expression stops as soon as it finds a match.
  • The next() method returns the value for the first matching element.

Using filter() (Alternative)

my_dict = {
'First_Name': 'Tom',
'Last_Name': 'Nolan',
'language': 'Python'
}

partial_key = 'name'
matching_values = dict(
filter(
lambda item: partial_key.lower() in item[0].lower(),
my_dict.items()
)
)
print(matching_values) # Output: {'First_Name': 'Tom', 'Last_Name': 'Nolan'}
  • The filter function takes a function that will perform the filtering, and an iterable, then performs the filtering operation and returns a filter object which is then converted to a dictionary.

Accessing Values Where Key Starts With a Given String

my_dict = {
'name_first': 'Tom',
'name_last': 'Nolan',
'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) # Output: ['Tom', 'Nolan']
  • The list comprehension will return all values that are associated with keys that start with a specific string.