Last updated: Apr 9, 2024
Reading timeยท3 min
To add items to a dictionary in a loop:
for
loop to iterate over a sequence.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)
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.
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: