【问题标题】:Iterating through and mutating dictionary遍历和变异字典
【发布时间】:2017-09-16 08:12:06
【问题描述】:

我在遍历和修改字典时遇到了问题...

假设我有一本字典:

dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}

我想遍历 dict1,使用其中的数据构建第二个字典。完成dict1 中的每个条目后,我将其删除。

在伪代码中:

dict2 = {}

for an entry in dict1:
    if key is A or B:
        dict2[key] = dict1[key]   # copy the dictionary entry
    if key is C:
        do this...
    otherwise:
        do something else...
    del dict1[key]

我知道在循环中改变可迭代对象的长度会导致问题,而上述实现可能并不简单。

this question 这个问题的答案似乎表明我可以使用keys() 函数,因为它返回一个动态对象。我因此尝试过:

for k in dict1.keys():
    if k == A or k == B:
        dict2[k] = dict1[k]
    elif k == C:
        dothis()
    else:
        dosomethingelse()
    del dict1[k]

但是,这只是给出:

'RuntimeError: 迭代期间字典大小改变'

在第一次删除之后。我也尝试过使用iter(dict1.keys()),但遇到了同样的错误。

因此我有点困惑,可以提出一些建议。谢谢

【问题讨论】:

标签: python dictionary


【解决方案1】:

只需使用.keys() 方法创建一个独立的键列表。

这是您的 Python 2.7 代码的工作版本:

>>> dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}
>>> dict2 = {}
>>> for key in dict1.keys():     # this makes a separate list of keys
        if key in ('A', 'B'):
            dict2[key] = dict1[key]
        elif key == 'C':
            print 'Do this!'
        else:
            print 'Do something else'
        del dict1[key]

Do this!
Do something else
>>> dict1
{}
>>> dict2
{'A': 'first', 'B': 'second'}   

对于 Python 3,在 .keys() 周围添加 list() 并使用打印功能:

>>> dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}
>>> dict2 = {}
>>> for key in list(dict1.keys()):     # this makes a separate list of keys
        if key in ('A', 'B'):
            dict2[key] = dict1[key]
        elif key == 'C':
            print('Do this!')
        else:
            print('Do something else')
        del dict1[key]

Do this!
Do something else
>>> dict1
{}
>>> dict2
{'A': 'first', 'B': 'second'}   

【讨论】:

    【解决方案2】:

    为什么不简单地使用 dict1.clear()? 请注意,在您的循环中,您每次迭代都会删除每个元素?

    我能想到的一个简化(和幼稚)的解决方案是

    delkeys=[]
    dict2 = {}
    
    for an entry in dict1:
      if key is A or B:
        dict2[key] = dict1[key]         # copy the dictionary entry
      if key is C:
        do this...
      elif:
        do something else...
      delkeys.append(key)
    
    for x in delkeys:
       del dict1[x]
    

    【讨论】:

      猜你喜欢
      • 2015-12-10
      • 2016-06-25
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      相关资源
      最近更新 更多