Skip to main content

How to Access Dictionary Keys and Values with Variables in Python

This guide explains how to use variables to access dictionary keys and values in Python, including how to handle nested dictionaries, and how to safely access keys that may not exist.

Accessing Dictionary Values Using a Variable for the Key

The most common use case is to store a key in a variable and then use that variable to access the corresponding value:

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

key_variable = 'name'
value = my_dict[key_variable] # Access using the variable
print(value) # Output: Tom Nolan

key_variable = 'site' # Different Key
print(my_dict[key_variable]) # Output: tutorialreference.com
  • This is the most direct approach when you want to use the variable to access the dictionary.
  • If the keys are strings and the variable that stores the key is an integer, the key will have to be converted to a string using str().
my_dict = {
'1': 'Tom',
'2': 'Nolan'
}
variable = 1
print(my_dict[str(variable)]) # Output: Tom
  • If you don't convert it to a string before accessing the dictionary, you will get a KeyError.

Handling Missing Keys with in

If you're unsure whether a key exists, always check first using the in operator to avoid a KeyError:

key_variable = 'missing_key'
if key_variable in my_dict:
value = my_dict[key_variable]
print(value)
else:
print(f"Key '{key_variable}' not found in dictionary.")

Handling Missing Keys with dict.get()

A more concise way to handle missing keys is to use the dict.get() method, which allows you to specify a default value:

key_variable = 'missing_key'
value = my_dict.get(key_variable, 'Default Value')
print(value) # Output: Default Value
  • The .get() method will not throw an exception if the key is not in the dictionary. Instead, it will either return the value assigned to that key if it exists, or the default value (by default the default value is None).

Accessing Nested Dictionaries

You can use variables to access keys at multiple levels in nested dictionaries:

my_dict = {
'first_name': 'Tom',
'last_name': 'Nolan',
'site': 'tutorialreference.com',
'address': {
'country': 'Example'
}
}

variable = 'site'
print(my_dict[variable]) # Output: tutorialreference.com

variable2 = 'address'
variable3 = 'country'

print(my_dict[variable2][variable3]) # Output: Example
  • The key is stored in a variable, which is then used to access a value in the dictionary.

Getting Dictionary Keys and Values as Variables

Iterating with for Loops

To get all keys and values as separate variables during iteration, use a for loop with dict.items():

my_dict = {
'first_name': 'Tom',
'last_name': 'Nolan',
'site': 'tutorialreference.com'
}

for key, value in my_dict.items():
print(key, value) # Iterating through the dictionary, and assigning items to variables

Output:

first_name Tom
last_name Nolan
site tutorialreference.com
  • The my_dict.items() returns key-value pairs from the dictionary.

Storing Specific Keys or Values in Variables

To store a specific key or value in a variable, convert the dictionary's keys or values to a list and then access by index:

my_dict = {
'first_name': 'Tom',
'last_name': 'Nolan',
'site': 'tutorialreference.com'
}

first_key = list(my_dict)[0] # Convert to list of keys and take by index.
print(first_key) # Output: first_name

first_value = list(my_dict.values())[0] # Convert values to list, take by index
print(first_value) # Output: Tom