2017-04-19 116 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]