Assign a dictionary Key or Value to variable in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
4 min

banner

# Table of Contents

  1. Assign a dictionary value to a Variable in Python
  2. Assign dictionary key-value pairs to variables in Python
  3. Assign dictionary key-value pairs to variables using exec()

# Assign a dictionary value to a Variable in Python

Use bracket notation to assign a dictionary value to a variable, e.g. first = my_dict['first_name'].

The left-hand side of the assignment is the variable's name and the right-hand side is the value.

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

assign dictionary value to variable

The code for this article is available on GitHub

The first example uses square brackets to access a dictionary key and assigns the corresponding value to a variable.

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

If you need to access the dictionary value using an index, use the dict.values() method.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } first = list(my_dict.values())[0] print(first) # ๐Ÿ‘‰๏ธ 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.

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())

We had to use the list() class to convert the view object to a list because view objects are not subscriptable (cannot be accessed at an index).

You can use the same approach if you have the key stored in a variable.

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

If you try to access a dictionary key that doesn't exist using square brackets, you'd get a KeyError.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # โ›”๏ธ KeyError: 'first' first = my_dict['first']

On the other hand, the dict.get() method returns None for non-existent keys by default.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } first = my_dict.get('first_name') print(first) # ๐Ÿ‘‰๏ธ Bobby first = my_dict.get('first') print(first) # ๐Ÿ‘‰๏ธ None
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', } print(my_dict.get('site')) # ๐Ÿ‘‰๏ธ bobbyhadz.com print(my_dict.get('another')) # ๐Ÿ‘‰๏ธ None print(my_dict.get('another', 'default value')) # ๐Ÿ‘‰๏ธ default value

If you need to assign the key-value pairs of a dictionary to variables, update the locals() dictionary.

# Assign dictionary key-value pairs to variables in Python

Update the locals() dictionary to assign the key-value pairs of a dictionary to variables.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # โœ… Using locals() locals().update(my_dict) print(first_name) # ๐Ÿ‘‰๏ธ Bobby print(site) # ๐Ÿ‘‰๏ธ bobbyhadz.com # --------------------------------------- # โœ… Using exec (only if data is trusted) for key, value in my_dict.items(): exec(key + '=value') print(first_name) # ๐Ÿ‘‰๏ธ Bobby print(site) # ๐Ÿ‘‰๏ธ bobbyhadz.com

assign dictionary key value pairs to variables

The code for this article is available on GitHub

The first example uses the locals() dictionary to assign the key-value pairs of a dictionary to local variables.

The locals() function returns a dictionary that contains the current scope's local variables.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd512e25de0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None, 'my_dict': {'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com'}} print(locals())

The dict.update method updates the dictionary with the key-value pairs from the provided value.

main.py
my_dict = {'name': 'Alice'} # โœ… Pass dictionary to the update() method my_dict.update({'name': 'bobbyhadz', 'age': 30}) print(my_dict) # ๐Ÿ‘‰๏ธ {'name': 'bobbyhadz', 'age': 30}
The code for this article is available on GitHub

You can access the variables directly after calling the dict.update() method.

main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } locals().update(my_dict) print(first_name) # ๐Ÿ‘‰๏ธ Bobby print(site) # ๐Ÿ‘‰๏ธ bobbyhadz.com
If you get linting errors when trying to access the variables, consider using the SimpleNamespace class.
main.py
from types import SimpleNamespace my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } namespace = SimpleNamespace(**my_dict) print(namespace.first_name) # ๐Ÿ‘‰๏ธ Bobby print(namespace.site) # ๐Ÿ‘‰๏ธ bobbyhadz.com

The SimpleNamespace class can be initialized with keyword arguments.

The keys of the dictionary are accessible as attributes on the namespace object.

Alternatively, you can use the exec() function.

# Assign dictionary key-value pairs to variables using exec()

This is a three-step process:

  1. Iterate over the dictionary's items.
  2. Use the exec() function to assign each key-value pair to a variable.
  3. The exec() function supports dynamic execution of Python code.
main.py
my_dict = { 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', } for key, value in my_dict.items(): exec(key + '=value') print(first_name) # ๐Ÿ‘‰๏ธ Bobby print(site) # ๐Ÿ‘‰๏ธ bobbyhadz.com

assign dictionary key value pairs to variables using exec

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, we use the exec() function to assign the current key-value pair to a variable.

Make sure to only use this approach if you can trust the data stored in the dictionary. Never use the exec() function with untrusted user input.

The exec() function supports dynamic execution of Python code.

The function takes a string, parses it as a suite of Python statements and runs the code.

Which approach you pick is a matter of personal preference. I'd go with the SimpleNamespace class to avoid any linting errors for trying to access undefined variables.

# 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