Adding items to a Dictionary in a Loop in Python

avatar
Borislav Hadzhiev

Last updated: Feb 21, 2023
3 min

banner

# Table of Contents

  1. Adding items to a Dictionary in a Loop in Python
  2. Adding items to a Dictionary in a Loop based on a condition
  3. Using lists for the values of the dictionary

# 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
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 loop

The 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.

# Adding items to a Dictionary in a Loop based on a condition

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)

add items to dictionary in loop based on condition

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.

# Using lists for the values of the dictionary

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)

using lists for values of the dictionary

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': 'bobby hadz', 'age': 30}) print(my_dict) # ๐Ÿ‘‰๏ธ {'name': 'bobby hadz', 'age': 30}

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

I've also written an article on how to add elements to a list in a loop.

# 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