简体   繁体   English

如何迭代动态对象?

[英]How to iterate over a dynamic object?

I have some code that iterates over the values of a dictionary. 我有一些代码可以迭代字典的值。 If the value meets certain conditions, it is deleted from the dictionary. 如果值满足特定条件,则将其从字典中删除。 Those conditions are contingent on the existence of other values in the dictionary. 这些条件取决于字典中其他值的存在。 This is why I don't want to just copy the old dictionary and make deletions, then re-attribute it. 这就是为什么我不想只复制旧字典并进行删除,然后重新定义它。

When I try to run it, I get an error that the size of the dictionary changed while iterating it. 当我尝试运行它时,我得到一个错误,字典的大小在迭代时发生了变化。 Is there a way to iterate over a dictionary that allows it to change size, and the existence of keys and values, while it is iterating? 有没有办法迭代一个允许它改变大小的字典,以及键和值的存在,而它是迭代的?

Build a new dictionary which contains the keys you want to keep . 构建一个包含要保留的键的新词典。 This can be done with a dictionary comprehension, or a manual for loop. 这可以通过字典理解或手动循环来完成。

Here's a comprehension: 这是一个理解:

return {k: v for k, v in my_dict.items() if some-condition}

Here's a manual loop: 这是一个手动循环:

result = {}
for k, v in my_dict.items():
    if some-condition:
        result[k] = v
return result

Well, yes you can iterate on by the keys (Python3)! 好吧,是的,你可以通过键(Python3)进行迭代! Take a look: 看一看:

>>> dc
{1: 'aze', 3: 'poi', 4: 'mlk'}
>>> dc = {1:"aze", 2:"qsd", 3:"poi", 4:"mlk"}
>>> dc
{1: 'aze', 2: 'qsd', 3: 'poi', 4: 'mlk'}
>>> keys = list(dc.keys())
>>> keys
[1, 2, 3, 4]
>>> for k in keys:
    if "q" in dc[k]:
        del dc[k]


>>> dc
{1: 'aze', 3: 'poi', 4: 'mlk'}
>>> 

You can iterate over the keys instead of over the dict itself. 您可以遍历键而不是字典本身。 In the following example, all values that are odd-numbered are removed from the dict: 在以下示例中,将从dict中删除所有奇数编号的值:

>>> a = {'a': 12,  'b': 3, 'c': 14}
>>> for key in list(a.keys()):
        if a[key] % 2 == 0:
            del a[key]
>>> a
{'b': 3}

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

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