2017-04-19 198 views
2

我遇到的问题,通过迭代和修改,字典...通过迭代和变异字典

说我有一本字典:

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: dictionary changed size during iteration'

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

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

+0

它似乎在循环结束时dict1将始终为空。那么当你完成循环时,你可以通过简单地覆盖dict1来解决问题吗? – Jonas

+0

http://stackoverflow.com/questions/12753351/removing-one-or-multiple-keys-from-a-dictionary http://stackoverflow.com/questions/8995611/removing-multiple-keys-from-a-字典安全 –

+0

遍历list(dict1.keys())'但是为什么你必须逐个删除键?循环之后只需要'dict1.clear()'。 –

回答

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()周围,使用打印功能:

>>> 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'} 
3

为什么不简单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]