[英]How to merge items belonging to the same key in list of dictionaries in python?
[英]How to merge the items of list if they are same and append if items are not same in Python
我有一個包含以下dict
數據的列表tags
tags = [ {'Time': 1, 'Name': 'John'} ]
我從函數中獲取tags
值。 有時收到的值具有相同的Name
因此在這種情況下,我需要簡單地獲取其Time
值並更新列表。 例如,如果收到以下數據:
tags = [ {'Time': 4, 'Name': 'John'} ]
在這種情況下,由於Name
是相同的,所以我將簡單地獲取Time
值並更新tags
列表,因此輸出將是:
output = [ {'Time': 4, 'Name': 'John'} ]
時間已從 1 更改為 4。但是假設收到了一個新Name
,例如以下:
tags = [ {'Time': 10, 'Name': 'John'}, {'Time': 6, 'Name': 'Karan'} ]
所以在這種情況下, John
時間將被更新, Karan
時間數據將被附加到列表中,因此輸出將是
output = [ {'Time': 10, 'Name': 'John'}, {'Time': 6, 'Name': 'Karan'} ]
因此,對於 John,我們更新了時間並添加了 Karan 數據。
我有output_tags
作為dict
,其中有一個tags
作為list
。 我正在做以下事情:
output_tags['Tags'].clear()
for tag in tags:
output_tags['Tags'].append(tag)
現在上面的代碼正在清除我們在output_tags['Tags']
任何數據,然后簡單地附加所有數據。 因此,通過這種方式,我們將更新相同的Name
時間並附加收到的任何新Name
。
但是使用此代碼,我正在清除我以前擁有的任何數據。 例如,前一段時間我收到了Ellis
數據,但現在我沒有收到Ellis
數據。 我仍然需要保留Ellis
數據,但它已被清除。 有沒有其他方法可以解決這個問題。 請幫忙。 謝謝
您可以合並兩個標簽列表:
from collections import defaultdict
tags = [ {'Time': 10, 'Name': 'John'}, {'Time': 6, 'Name': 'Karan'} ]
new_tags = [ {'Time': 30, 'Name': 'Bob'}, {'Time': 40, 'Name': 'Karan'} ]
d = defaultdict(dict)
# using defaultdict(dict), whatever the key your using, it will be initiated with a dict : `d['random_key'] == {}` is True
# we fill d with all tags and new_tags using `Name` as key
for list_ in (tags, new_tags):
for obj in list_:
# if `obj['Name']` has already been set, it is updated
# otherwise it is added
d[obj['Name']].update(obj)
# display only values and make it a list
results = list(d.values())
print(results)
# [{'Time': 10, 'Name': 'John'}, {'Time': 40, 'Name': 'Karan'}, {'Time': 30, 'Name': 'Bob'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.