小编PyN*_*oob的帖子

字典在迭代过程中更改了大小-代码在Py2中有效,而在Py3中无效

我有以下示例代码:

k_list = ['test', 'test1', 'test3']

def test(*args, **kwargs):
    for k, value in kwargs.items():
        if k in k_list:
            print("Popping k = ", k)
            kwargs.pop(k, None)
    print("Remaining KWARGS:", kwargs.items())

test(test='test', test1='test1', test2='test2', test3='test3')
Run Code Online (Sandbox Code Playgroud)

在Python 2.7.13中,这完全可以打印出我所期望的内容,并且仍然在kwargs

('Popping k = ', 'test')
('Popping k = ', 'test1')
('Popping k = ', 'test3')
('Remaining KWARGS:', [('test2', 'test2')])
Run Code Online (Sandbox Code Playgroud)

但是,在Python 3.6.1中,此操作失败:

Popping k =  test
Traceback (most recent call last):
  File "test1.py", line 11, in <module>
    test(test='test', test1='test1', test2='test2', test3='test3')
  File "test1.py", line 5, …
Run Code Online (Sandbox Code Playgroud)

python dictionary python-2.7 python-3.x

3
推荐指数
2
解决办法
3218
查看次数

标签 统计

dictionary ×1

python ×1

python-2.7 ×1

python-3.x ×1