Using variables to add items to a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 19, 2022

banner

Photo from Unsplash

Using variables to add items to a Dictionary in Python #

Use square brackets to add items to a dictionary using variables, e.g. my_dict[key] = value. The key between the square brackets and the value on the right-hand side of the assignment can be stored in a variable.

main.py
my_dict = {} key = 'site' value = 'bobbyhadz.com' my_dict[key] = value # 👇️ {'site': 'bobbyhadz.com'} print(my_dict)

We used bracket notation to add an item to a dictionary using variables.

The key, the value or both can be stored in a variable.

main.py
my_dict = {} value = 'bobbyhadz.com' my_dict['site'] = value # 👇️ {'site': 'bobbyhadz.com'} print(my_dict)

You can use a for loop if you need to add multiple items to a dictionary using variables.

main.py
my_dict = {} keys = ['first_name', 'last_name', 'site'] values = ['bobby', 'hadz', 'bobbyhadz.com'] for index, key in enumerate(keys): my_dict[key] = values[index] # 👇️ {'first_name': 'bobby', 'last_name': 'hadz', 'site': 'bobbyhadz.com'} print(my_dict)

We used the enumerate() function to get access to the index of the current iteration.

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

main.py
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 bobby, 1 hadz, 2 com

On each iteration, we use bracket notation to add the key and the corresponding value to the 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.