我有一個非常大的字典串列,看起來像這樣(我展示了一個簡化版本):
list_of_dicts:
[{'ID': 1234,
'Name': 'Bobby',
'Animal': 'Dog',
'About': [{'ID': 5678, 'Food': 'Dog Food'}]},
{'ID': 5678, 'Food': 'Dog Food'},
{'ID': 91011,
'Name': 'Jack',
'Animal': 'Bird',
'About': [{'ID': 1996, 'Food': 'Seeds'}]},
{'ID': 1996, 'Food': 'Seeds'},
{'ID': 2007,
'Name': 'Bean',
'Animal': 'Cat',
'About': [{'ID': 2008, 'Food': 'Fish'}]},
{'ID': 2008, 'Food': 'Fish'}]
我想洗掉包含與嵌套在“關于”條目中的 ID 相同的 ID 的字典。例如,“ID”2008 已經嵌套在嵌套的“關于”值中,因此我想洗掉該字典。
我有一些代碼可以做到這一點,對于這個特定的例子,它可以作業。但是,我擁有的資料量要大得多,除非我運行幾次,否則 remove() 函式似乎不會洗掉所有條目。
關于如何更好地做到這一點的任何建議?
我的代碼:
nested_ids = [5678, 1996, 2008]
for i in list_of_dicts:
if i['ID'] in nested_ids:
list_of_dicts.remove(i)
期望的輸出:
[{'ID': 1234,
'Name': 'Bobby',
'Animal': 'Dog',
'About': [{'ID': 5678, 'Food': 'Dog Food'}]},
{'ID': 91011,
'Name': 'Jack',
'Animal': 'Bird',
'About': [{'ID': 1996, 'Food': 'Seeds'}]},
{'ID': 2007,
'Name': 'Bean',
'Animal': 'Cat',
'About': [{'ID': 2008, 'Food': 'Fish'}]}]
uj5u.com熱心網友回復:
您可以使用串列推導:
cleaned_list = [d for d in list_of_dicts if d['ID'] not in nested_ids]
uj5u.com熱心網友回復:
發生這種情況是因為我們在迭代時修改了字典,所以為了避免我們可以將所需的值復制到新的字典中,如下所示
filtered_dicts = []
nested_ids = [5678, 1996, 2008]
for curr in list_of_dicts:
if curr['ID'] not in nested_ids:
filtered_dicts.append(curr)
uj5u.com熱心網友回復:
問題是,當您洗掉串列的成員時,您正在更改該索引之后所有內容的索引,因此您應該重新排序要反向洗掉的索引,以便從串列的后面開始
所以你需要做的就是以相反的順序遍歷串列:
for i in list_of_dicts[::-1]:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/525167.html
標籤:Python列表循环字典
