HOWTO · Python
How to Add Key-Value Pairs to a Dictionary Within a Loop in Python
Learn how to add Key-Value pairs to a Dictionary within a loop in Python.
On this page
Dictionary assignment adds or updates an entry: place dictionary[key] = value inside a loop. When keys and values are in separate iterables, pair them with zip() in a for loop. Use a while loop when the index itself matters.
Add Key-Value Pairs to a Dictionary Within a Loop
Start with a dictionary, then assign each key to its corresponding value as the loop visits each pair. The values may be different kinds of Python objects; the keys must be hashable. The following example pairs names with scores:
Pair Keys and Values with zip()
zip(keys, values) yields a pair from each iterable on every iteration. Run this example:
keys = ["Ada", "Linus", "Grace"]
values = [98, 91, 100]
scores = {}
for key, value in zip(keys, values):
scores[key] = value
print(scores)
{'Ada': 98, 'Linus': 91, 'Grace': 100}
The assignment stores each score under its paired name. This pattern also works when the values are lists, functions, or other objects; only dictionary keys have the hashability requirement.
Use a while Loop When You Need Indexes
An index-based loop is useful when another operation needs the position. Set a stopping point and increment the index on every pass:
keys = ["Ada", "Linus", "Grace"]
values = [98, 91, 100]
scores = {}
index = 0
limit = min(len(keys), len(values))
while index < limit:
scores[keys[index]] = values[index]
index += 1
Here, limit ensures the loop only accesses positions present in both lists. For ordinary pairing, for key, value in zip(keys, values) is shorter and avoids managing the index yourself.
Handle Unequal Inputs and Existing Keys
By default, zip() stops as soon as its shortest iterable is exhausted. Any unmatched items in a longer iterable are left out. If every key must have a value, compare the input lengths before looping and decide how your program should handle a mismatch.
Assigning to a key already in the dictionary replaces that key’s previous value; it does not create a second entry with the same key. If you need to keep both values, store a collection as the value and append to it instead. A key must be hashable, so strings, numbers, and tuples of hashable items can be used, while mutable lists and dictionaries cannot.
Print the Result and Understand Complexity
Use print(scores) to inspect a small dictionary, or iterate over scores.items() to format each key and value. A simple dictionary representation is deterministic for the values in the example. Custom objects may display a representation containing an address, so print specific attributes when you need readable, repeatable output.
For m pairs, the loop performs m assignments, taking O(m) time on average because each dictionary assignment is O(1) on average. This is average-case behavior; collisions can make individual assignments slower. The output dictionary holds up to m distinct keys, so it uses O(m) additional space. The zip() iterator itself uses constant auxiliary space. If a dictionary already contains d entries, it retains those entries unless a paired key replaces its value; its final size is at most d + m.