Access dictionary values with Key starting with given String

avatar

Borislav Hadzhiev

Last updated: Sep 19, 2022

banner

Photo from Unsplash

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' } # ✅ Get all values of keys starting with given string 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'] # --------------------------------------------------- # ✅ Get first value of key starting with given string value = next( (value for key, value in my_dict.items() if key.lower().startswith(key_prefix.lower())), None ) print(value) # 👉️ Bobby

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.

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

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.

If you need to access the dictionary values with a key that contains a given string, use the in operator.
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']

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