[英]from list of dictionaries make a dict such that the same value in the dictionaries will become the key and the values are the items which are left
[英]Python: remove dictionaries from a list which have same value for a key so that the values of that key are unique for all the dictionaries in the list
假設我有以下詞典列表:
givenValues=[
{'id': '0001', 'name': 'me'},
{'id': '0002', 'name': 'me'},
{'id': '0001', 'name': 'you'},
{'id': '0003', 'name': 'hi'},
{'id': '0001', 'name': 'they'},
{'id': '0002', 'name': 'me'},
{'id': '0002', 'name': 'me'}
]
我想保留每個唯一 ID 的第一個,並從列表中刪除所有其他詞典,這樣的結果是
[
{'id': '0001', 'name': 'me'},
{'id': '0002', 'name': 'me'},
{'id': '0003', 'name': 'hi'}
]
到目前為止,我已經嘗試了以下。 如果列表中的字典排列不同但並非總是如此,則某些嘗試確實有效:
tempList=[]
for i in range(len(givenValues)):
for j in range(i+1, len(givenValues)):
if givenValues[i]['id']==givenValues[j]['id']:
tempList.append(givenValues[j])
for item in tempList:
if item in givenValues:
givenValues.remove(item)
結果:
[
{'id': '0001', 'name': 'me'},
{'id': '0003', 'name': 'hi'}
]
for i in range(len(givenValues)):
if i<len(givenValues):
for j in range(i+1, len(givenValues)):
if i<len(givenValues) and givenValues[i]['id']==givenValues[j]['id']:
givenValues.remove(givenValues[j])
結果
[
{'id': '0001', 'name': 'me'},
{'id': '0003', 'name': 'hi'},
{'id': '0001', 'name': 'they'},
{'id': '0002', 'name': 'me'}
]
請幫我解決這個問題。
這是一個可能的解決方案:
data = [
{"id": "0001", "name": "me"},
{"id": "0002", "name": "me"},
{"id": "0001", "name": "you"},
{"id": "0003", "name": "hi"},
{"id": "0001", "name": "they"},
{"id": "0002", "name": "me"},
{"id": "0002", "name": "me"},
]
selected = {}
for item in data:
if item["id"] not in selected:
selected[item["id"]] = item
output = list(selected.values())
print(output)
我們使用字典來跟蹤唯一項,並且我們利用了字典的.values()
方法按插入順序返回項的事實(因此這保留了我們在中找到項的順序)原始列表)。
上面的代碼輸出:
[{'id': '0001', 'name': 'me'}, {'id': '0002', 'name': 'me'}, {'id': '0003', 'name': 'hi'}]
這是解決此問題的另一種方法,使用itertools.groupby
:
import itertools
data = [
{"id": "0001", "name": "me"},
{"id": "0002", "name": "me"},
{"id": "0001", "name": "you"},
{"id": "0003", "name": "hi"},
{"id": "0001", "name": "they"},
{"id": "0002", "name": "me"},
{"id": "0002", "name": "me"},
]
output = []
for k, g in itertools.groupby(sorted(data, key=lambda item: item['id']), lambda item: item['id']):
output.append(next(g))
print(output)
這會產生相同的 output。它的工作原理是按id
對列表中的項目進行分組,然后從每個組中取出第一個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.