Sometimes, we want to modify a Python dict while iterating over it.
In this article, we’ll look at how to modify a Python dict while iterating over it.
How to modify a Python dict while iterating over it?
To modify a Python dict while iterating over it, we can use the items
method to get the key and value.
For instance, we write
prefix = 'item_'
t = {'f1': 'ffw', 'f2': 'fca'}
t2 = dict()
for k,v in t.items():
t2[k] = prefix + v
to loop through the key value pairs in t
with t.items()
and the for loop.
In it, we set t2[k]
to the prefix + v
where v
is the value in the t
dict.
t2
is a new dict so we can modify it in the for loop.
Conclusion
To modify a Python dict while iterating over it, we can use the items
method to get the key and value.