Farhan Nawaz
Farhan Nawaz

Reputation: 105

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?

Upvotes: 0

Views: 70

Answers (3)

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

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'))]

Upvotes: 0

Kholdarbekov
Kholdarbekov

Reputation: 1150

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)

Upvotes: 1

user2952903
user2952903

Reputation: 385

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)

Upvotes: 0

Related Questions