简体   繁体   English

迭代python dict的值并同时更新

[英]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. 我想知道如何迭代值并同时更新python的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(). 它包括一个列表和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: 只需在dict.values() list()上使用list()来创建一个副本,并避免RuntimeError: dictionary changed size during iteration异常RuntimeError: dictionary changed size during iteration获取RuntimeError: dictionary changed size during iteration

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. 这当然不会更新原始字典,只需扩展values列表。

This assumes you are using Python 3; 假设您使用的是Python 3; in Python 2, dict.values() already returns a list copy, not a dictionary view; 在Python 2中, dict.values()已经返回一个列表副本,而不是字典视图; you'd use values = First_dict.values() directly instead. 你可以直接使用values = First_dict.values()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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