Adding items to a Dictionary in a Loop in Python

avatar

Borislav Hadzhiev

Last updated: Sep 21, 2022

banner

Photo from Unsplash

Adding items to a Dictionary in a Loop in Python #

To add items to a dictionary in a loop:

  1. Use a for loop to iterate over a sequence.
  2. Optionally, check if a certain condition is met.
  3. Use bracket notation to add items to the dictionary.
main.py
# ✅ add items to dictionary in a loop my_list = [('first', 'bobby'), ('last', 'hadz'), ('site', 'bobbyhadz.com')] my_dict = {} for item in my_list: my_dict[item[0]] = item[1] # 👇️ {'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com'} print(my_dict) # ---------------------------------------------------------- # ✅ add items to dictionary in a loop (with condition) my_list = [('site', 'bobbyhadz.com'), ('last', 'hadz'), ('site', 'google.com')] my_dict = {} for item in my_list: if item[0] not in my_dict: my_dict[item[0]] = item[1] # 👇️ {'site': 'bobbyhadz.com', 'last': 'hadz'} print(my_dict)

The first example iterates over a list of tuples and adds new key-value pairs to a dictionary.

You could be iterating over any other data structure, but the concept is the same.

main.py
my_list = [('first', 'bobby'), ('last', 'hadz'), ('site', 'bobbyhadz.com')] my_dict = {} for item in my_list: my_dict[item[0]] = item[1] # 👇️ {'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com'} print(my_dict)

On each iteration, we access the tuple item at index 0 and use it for the key and use the tuple item at index 1 for the value.

Something you'll often have to do is check for a condition before adding items to a dictionary in a loop.
main.py
my_list = [('site', 'bobbyhadz.com'), ('last', 'hadz'), ('site', 'google.com')] my_dict = {} for item in my_list: if item[0] not in my_dict: my_dict[item[0]] = item[1] # 👇️ {'site': 'bobbyhadz.com', 'last': 'hadz'} print(my_dict)

We used the not in operator to check if the key is not present in the dictionary before adding it.

When used with a dictionary, the in and not in operators check for the existence of the specified key in the dict object.

If the key is not already in the dictionary, we add a new item with the specified key.

Alternatively, you can use lists for the values in the dictionary.

If the key is already present in the dictionary, we append an item to the list, otherwise, we set the key to a list containing the value.

main.py
my_list = [['site', 'bobbyhadz.com'], ['last', 'hadz'], ['last', 'test'], ['site', 'google.com']] my_dict = {} for item in my_list: if item[0] not in my_dict: my_dict[item[0]] = [item[1]] else: my_dict[item[0]].append(item[1]) # 👇️ {'site': ['bobbyhadz.com', 'google.com'], 'last': ['hadz', 'test']} print(my_dict)

On each iteration, our if statement checks if the key is not in the dictionary.

If the key is not in the dictionary, we set the key to a list containing the value.

If the key is already in the dictionary, we use the list.append() method to add another value to the list.

If you need to add or update multiple keys in the dictionary in a single statement, use the dict.update() method.

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

main.py
my_dict = {'name': 'Alice'} my_dict.update({'name': 'bobbyhadz', 'age': 30}) print(my_dict) # 👉️ {'name': 'bobbyhadz', 'age': 30}

The method overrides the dictionary's existing keys and returns None.

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.