简体   繁体   中英

How can I merge two lists of dicts in python with potentially different key-value pairs?

Say I have two list of dicts, both of which are KVPs in different dicts.

oldItemsBought = [{
   "name" : <item name>,
   "quantity": <item quantity>,
   "billed": <item bill amount (qty * price)>
}
{
   "name" : <item name>,
   "quantity": <item quantity>,
   "billed": <item bill amount (qty * price)>
}.....]
newItemsBought = [{
   "name" : <item name>,
   "quantity": <item quantity>,
   "billed": <item bill amount (qty * price)>
}
{
   "name" : <item name>,
   "quantity": <item quantity>,
   "billed": <item bill amount (qty * price)>
}.....]

Here, the "name" keys can have same or different values in either list (old or new items respectively), but the quantities need to be merged (If keys are same, add quantities), and bill Amounts need to be added.

Is there an easier way of doing this append-or-update operation?

newList = []

is_dublicate = False

for item in newItemBought:
    for old_item in oldItemsBought:
        if item['name'] == old_item['name']:
            old_item['quantity'] += item['quantity']
            newList.append(old_item)
            oldItemsBought.remove(old_item)
            is_dublicate = True
            break

    if not is_dublicate:
        newList.append(item)

    is_dublicate = False


for item in oldItemsBought:
    newList.append(item)


print(newList)
for olditem in oldItemsBought:
    for newitem in newItemsBought:
        if olditem["name"]==newitem["name"]:
            newitem["quantity"]+=olditem["quantity"]
            newitem["billed"]+=olditem["billed"]
            break
    else:
        print(olditem["name"],newitem["name"],olditem)
        newItemsBought.append(olditem)

Try using groupby to get all dictionaries sharing the same name:

from itertools import groupby
from operator import itemgetter

res = [{'name': k,
        'quantity': sum(item['quantity'] for item in g),
        'billed': sum(item['billed'] for item in g)}
       for k, g in groupby(oldItemsBought + newItemsBought, itemgetter('name'))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM