我收到以下錯誤:
RuntimeError: dictionary changed size during iteration.
我有以下嵌套字典:
devices = {
'devices': [
{
'id': 'XX',
'is_active': True,
'is_private_session': False,
'is_restricted': False,
'name': 'XX',
'type': 'Computer',
'volume_percent': 100
},
{
'id': 'XX',
'is_active': False,
'is_private_session': False,
'is_restricted': False,
'name': 'XX',
'type': 'Speaker',
'volume_percent': 62
}
]
}
我正在嘗試洗掉一些嵌套的鍵 值。這就是我正在嘗試的:
del_key_list = ['is_private_session', 'is_restricted', 'type', 'volume_percent']
for dictionary in devices['devices']:
for key in dictionary:
if key in del_key_list:
del dictionary[key]
我是否必須使用過濾器或反向串列 (list_of_keys_I_want_to_save)?
uj5u.com熱心網友回復:
您需要遍歷鍵的副本以避免在迭代期間更改字典的例外:
for dictionary in devices['devices']:
for key in list(dictionary.keys()): # note a list() here
if key in del_key_list:
del dictionary[key]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465150.html
標籤:Python python-3.x 列表 字典 python-3.9
上一篇:具有多索引的熊貓資料框到字典
下一篇:如何獲取dict中鍵的最大值?
