Using a variable to access a dictionary Key in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
4 min

banner

# Table of Contents

  1. Using a variable to access a dictionary Key in Python
  2. Get dictionary Key as a Variable in Python

# Using a variable to access a dictionary Key in Python

Use square brackets to access a dictionary key using a variable, e.g. my_dict[variable].

If the variable is an integer and the dictionary's keys are strings, convert the variable to a string when accessing a key, e.g. my_dict[str(variable)].

main.py
# ๐Ÿ‘‡๏ธ keys are strings my_dict = { '1': 'bobby', '2': 'hadz' } # ๐Ÿ‘‡๏ธ variable is an integer variable = 1 print(my_dict[str(variable)]) # ๐Ÿ‘‰๏ธ bobby

using variable to access dictionary key

The code for this article is available on GitHub

We used bracket notation to access a dictionary using a variable as the key.

If the dictionary's keys are strings and the variable is an integer, use the str() class to convert the variable to a string.

main.py
my_dict = { '1': 'bobby', '2': 'hadz' } variable = 1 print(my_dict[str(variable)]) # ๐Ÿ‘‰๏ธ bobby

convert integer to string to use as key

If you don't convert the variable to a string, you'll get a KeyError exception.

main.py
my_dict = { '1': 'bobby', '2': 'hadz' } variable = 1 # โ›”๏ธ KeyError: print(my_dict[variable])
A KeyError exception is raised when we use square brackets to access a key that doesn't exist.

# Using variables to access nested keys in a dictionary

You can use the same approach to access nested dictionaries using a variable as the key.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', 'address': { 'country': 'Example' } } variable = 'site' print(my_dict[variable]) # ๐Ÿ‘‰๏ธ bobbyhadz.com variable2 = 'address' variable3 = 'country' print(my_dict[variable2][variable3]) # ๐Ÿ‘‰๏ธ Example

using variables to access nested keys in dictionary

The code for this article is available on GitHub

# Using the dict.get() method instead

Alternatively, you can use the dict.get() method.

main.py
my_dict = { '1': 'bobby', '2': 'hadz' } variable = 1 print(my_dict.get(str(variable))) # ๐Ÿ‘‰๏ธ bobby # --------------------------------- my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', 'address': { 'country': 'Example' } } variable = 'site' print(my_dict.get(variable)) # ๐Ÿ‘‰๏ธ bobbyhadz.com

using dict get method instead

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.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } variable = 'site' print(my_dict.get(variable)) # ๐Ÿ‘‰๏ธ bobbyhadz.com variable2 = 'another' print(my_dict.get(variable2)) # ๐Ÿ‘‰๏ธ None print(my_dict.get(variable2, 'default value')) # ๐Ÿ‘‰๏ธ default value

In the last example, the specified key doesn't exist, so the provided default value is returned.

# Get dictionary Key as a Variable in Python

If you need to get a dictionary key as a variable:

  1. Use a for loop to iterate over the dictionary's items.
  2. Assign the key to a variable.
  3. The variable will store the key of the current iteration.
main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } # โœ… get dictionary keys and values as variables for key in my_dict: # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, my_dict[key]) for key, value in my_dict.items(): # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, value)

get dictionary key as variable

The code for this article is available on GitHub

The first example uses a for loop to iterate directly over the dictionary.

The key variable stores the key of the current iteration.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } for key in my_dict: # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, my_dict[key])

You can use square brackets if you need to access the corresponding value.

# Getting the dictionary's keys and values as variables

You can also use the dict.items() method to get the dictionary's keys and values as variables.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } for key, value in my_dict.items(): # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, value)
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_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } # ๐Ÿ‘‡๏ธ dict_items([('first_name', 'Bobby'), ('last_name', 'Hadz'), ('site', 'bobbyhadz.com')]) print(my_dict.items())

On each iteration, the key variable stores the key of the current iteration and the value variable stores the corresponding value.

# Storing a specific dictionary key or value in a variable

If you need to store a specific dictionary key in a variable, convert the dictionary to a list of keys and access the key at its index.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } first_key = list(my_dict)[0] print(first_key) # ๐Ÿ‘‰๏ธ first_name first_value = list(my_dict.values())[0] print(first_value) # ๐Ÿ‘‰๏ธ Bobby
The code for this article is available on GitHub

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

We used the list() class to convert the dictionary to a list of keys.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } print(list(my_dict)) # ๐Ÿ‘‰๏ธ ['first_name', 'last_name', 'site'] print(list(my_dict.keys())) # ๐Ÿ‘‰๏ธ ['first_name', 'last_name', 'site']

We could have also used the dict.keys() method to be more explicit.

The dict.keys() method returns a new view of the dictionary's keys.

If you need to store a specific dictionary value in a variable, convert the dictionary's values to a list and access the value at its index.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } first_value = list(my_dict.values())[0] print(first_value) # ๐Ÿ‘‰๏ธ Bobby

The dict.values() method returns a new view of the dictionary's values.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' } # ๐Ÿ‘‡๏ธ dict_values(['Bobby', 'Hadz', 'bobbyhadz.com']) print(my_dict.values())

View objects are not subscriptable (cannot be accessed at an index), so we had to convert the view object to a list before accessing a specific value.

I've also written an article on how to assign a dictionary key or value to a variable.

# 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