简体   繁体   中英

Iterating over the values of a python dict and simultaneous update

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM