Reputation: 2182
I wonder how to iterate over the values and update simultaneously a python's dict. Why the following code does not work?
for values in First_Dict.values():
if True:
Second_Dict= Function(values)
First_Dict.update(Second_Dict)
There is a solution, but it is not very elegant. It includes a list and iter(). Obviously, I do not care about the keys.
tempList = [i for i in First_Dict.values()]
iterator = iter(tempList)
while True:
try:
TempIterator = iterator.next()
except StopIteration:
break
if True:
Second_Dict= Function(values)
for j in Second_Dict.values():
tempList.append(j)
Upvotes: 0
Views: 989
Reputation: 1121844
You are overcomplicating things; just use list()
on dict.values()
to create a copy and avoid getting the RuntimeError: dictionary changed size during iteration
exception:
for value in list(First_Dict.values()):
if True:
First_Dict.update(Second_Dict)
If you need a dynamically growing list, store the list first, then loop:
values = list(First_dict.values())
for value in values:
if True:
values.extend(Second_Dict.values())
This of course does not update the original dictionary, just extend the values
list.
This assumes you are using Python 3; in Python 2, dict.values()
already returns a list copy, not a dictionary view; you'd use values = First_dict.values()
directly instead.
Upvotes: 2