Assign dictionary key-value pairs to variables in Python

avatar

Borislav Hadzhiev

Last updated: Sep 19, 2022

banner

Photo from Unsplash

Assign dictionary key-value pairs to variables in Python #

Update the locals() dictionary to assign the key-value pairs of a dictionary to variables, e.g. locals().update(my_dict). The statement will add the key-value pairs of the dictionary to the current scope's local 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

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}

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

To assign the key-value pairs of a dictionary to variables:

  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

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.

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.