迭代和改变字典

use*_*225 4 python dictionary

我在迭代和修改字典时遇到问题......

假设我有一本字典:

dict1 = {'A' : 'first', 'B' : 'second', 'C' : 'third', 'D' : 'fourth'}
Run Code Online (Sandbox Code Playgroud)

我想迭代 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]
Run Code Online (Sandbox Code Playgroud)

我知道改变循环中可迭代的长度会导致问题,并且上述内容可能不容易实现。

这个问题的答案似乎表明我可以使用该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]
Run Code Online (Sandbox Code Playgroud)

但是,这只是给出:

“运行时错误:字典在迭代期间更改了大小”

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

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

Ray*_*ger 5

只需使用该.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'}   
Run Code Online (Sandbox Code Playgroud)

对于 Python 3,在 周围添加list().keys()并使用 print 函数:

>>> 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'}   
Run Code Online (Sandbox Code Playgroud)