Create a dictionary using variables as keys in Python

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

Create a dictionary using variables as keys in Python #

To create a dictionary using variables as keys:

  1. Use a dict comprehension to iterate over the variable names.
  2. Use the eval() function to get the value of each variable.
  3. Return each key-value pair.
main.py
first_name = 'Borislav' last_name = 'Hadzhiev' site = 'bobbyhadz.com' # ✅ create dictionary from variables (using eval()) my_dict = {key: eval(key) for key in ['first_name', 'last_name', 'site']} # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com'} print(my_dict) # ------------------------------------------------------------------- # ✅ create dictionary from variables (using globals()) my_dict = {key: globals()[key] for key in ['first_name', 'last_name', 'site']} # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com'} print(my_dict)

We used a dict comprehension to iterate over a list containing the names of the variables.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.
main.py
first_name = 'Borislav' last_name = 'Hadzhiev' site = 'bobbyhadz.com' my_dict = {key: eval(key) for key in ['first_name', 'last_name', 'site']} # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com'} print(my_dict)

On each iteration, we assign the variable name to the key and use the eval() function to get the corresponding value.

The eval function takes an expression, parses it and evaluates it as a Python expression using the globals and locals dictionaries as the global and local namespace.

Note that you have to specify the names of the variables that will be used when creating the dictionary.

The eval() function should only be used with trusted code. Don't use eval() with user-generated data.

If you get linting errors when using eval(), use the globals() dictionary instead.

Create a dictionary using variables as keys using globals() #

  1. Use a dict comprehension to iterate over the variable names.
  2. Use the globals() dictionary to access the value of each variable.
  3. Return each key-value pair.
main.py
first_name = 'Borislav' last_name = 'Hadzhiev' site = 'bobbyhadz.com' my_dict = {key: globals()[key] for key in ['first_name', 'last_name', 'site']} # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com'} print(my_dict)

The globals function returns a dictionary that implements the current module namespace.

main.py
first_name = 'Borislav' last_name = 'Hadzhiev' site = 'bobbyhadz.com' globals_dict = globals() # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com', 'globals_dict': {...}, '__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f615db95de0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None} print(globals_dict)

We use bracket notation to access the value of each key and return the key-value pairs.

You can also use a for loop to achieve the same result.

main.py
first_name = 'Borislav' last_name = 'Hadzhiev' site = 'bobbyhadz.com' my_dict = {} for key in ['first_name', 'last_name', 'site']: my_dict[key] = globals()[key] # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com'} print(my_dict)

We used a for loop to iterate over a list containing the names of the variables and assigned each variable name and its value as dictionary items.

Alternatively, you can pass a collection of key-value pairs to the dict() class.

main.py
first_name = 'Borislav' last_name = 'Hadzhiev' site = 'bobbyhadz.com' my_dict = dict((key, globals()[key]) for key in ['first_name', 'last_name', 'site']) # 👇️ {'first_name': 'Borislav', 'last_name': 'Hadzhiev', 'site': 'bobbyhadz.com'} print(my_dict)

The dict() class can be passed an iterable of key-value pairs and returns a new dictionary.

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.