How to Add Items to Dictionaries in Loops
This guide covers how to efficiently add items to a dictionary within a loop in Python. We'll look at basic key-value insertion, handling potential duplicate keys, and building dictionaries where each key maps to a list of values. We'll use for
loops, conditional logic, and the powerful collections.defaultdict
for cleaner code.
Basic Key-Value Insertion in a Loop
The fundamental way to add items to a dictionary inside a loop is:
my_list = [
('first', 'tom'),
('last', 'nolan'),
('site', 'tutorialreference.com.com')
]
my_dict = {}
for key, value in my_list: # Tuple unpacking for clarity
my_dict[key] = value
print(my_dict)
# Output: {'first': 'tom', 'last': 'nolan', 'site': 'tutorialreference.com.com'}
- We initialize an empty dictionary,
my_dict
. - The
for
loop iterates throughmy_list
which contains key-value pairs in tuples. - The tuple values for key and value are unpacked in the for loop.
- Inside the loop,
my_dict[key] = value
adds the key-value pair to the dictionary. Ifkey
already exists, its value is overwritten.
Preventing Key Overwrites (Handling Duplicates)
If your data might contain duplicate keys, and you want to keep only the first occurrence, use the in
operator to check before inserting:
my_list = [
('site', 'tutorialreference.com.com'),
('last', 'nolan'),
('site', 'google.com') # Duplicate key 'site'
]
my_dict = {}
for key, value in my_list:
if key not in my_dict:
my_dict[key] = value
print(my_dict) # Output: {'site': 'tutorialreference.com.com', 'last': 'nolan'}
- Only values with keys that are not in the dictionary will be added.
Creating Dictionaries with List Values
A very common pattern is to build a dictionary where each key maps to a list of values.
Using setdefault()
(Less Recommended)
You can use setdefault()
, but it's less readable than the next option:
my_list = [['site', 'tutorialreference.com.com'], ['last', 'nolan'],
['last', 'test'], ['site', 'google.com']]
my_dict = {}
for key, value in my_list:
my_dict.setdefault(key, []).append(value)
# or my_dict.setdefault(key, []).extend([value])
print(my_dict)
# Output: {'site': ['tutorialreference.com.com', 'google.com'], 'last': ['nolan', 'test']}
my_dict.setdefault(key, [])
does two things:- If
key
is already inmy_dict
, it returns the existing value (which should be a list). - If
key
is not inmy_dict
, it insertskey
with a default value of[]
(an empty list) and then returns that empty list.
- If
- The append will work correctly in either case because you will always get a list as a result.
Using collections.defaultdict
(Recommended)
The collections.defaultdict
class is specifically designed for this scenario, and is much cleaner:
from collections import defaultdict
my_list = [['site', 'tutorialreference.com.com'], ['last', 'nolan'],
['last', 'test'], ['site', 'google.com']]
my_dict = defaultdict(list) # Specify that the default value is a list
for key, value in my_list:
my_dict[key].append(value) # No need to check if key exists!
print(my_dict)
# Output: defaultdict(<class 'list'>, {'site': ['tutorialreference.com.com', 'google.com'], 'last': ['nolan', 'test']})
defaultdict(list)
creates a dictionary-like object where, if you try to access a key that doesn't exist, it automatically creates that key and sets its value to an empty list (list()
is the "default factory").- This eliminates the need for the
if key not in my_dict:
check, making the code simpler and more efficient. - You can set multiple empty lists using a
for
loop.
a_dict = {}
keys = ['site_a', 'site_b', 'site_c']
for key in keys:
a_dict.setdefault(key, []) # Set empty list as default value.
print(a_dict) # Output: {'site_a': [], 'site_b': [], 'site_c': []}
Updating Multiple Keys with dict.update()
The dict.update()
method updates the dictionary with the key-value pairs from the provided value.
my_dict = {'name': 'alice'}
my_dict.update({'name': 'tom nolan', 'age': 30})
print(my_dict) # Output: {'name': 'tom nolan', 'age': 30}
- This method is used when you want to update multiple key-value pairs at once.
- The argument can be a dictionary, or an iterable of key-value pairs (such as tuples).