What is the most pythonic way to merge two list dictionaries please? Say I have two list of dictionaries as:
sold=[
{'dept': '001', 'sku': 'foo', 'qty': 100},
{'dept': '002', 'sku': 'bar', 'qty': 200},
{'dept': '003', 'sku': 'baz', 'qty': 300}
]
returns=[
{'dept': '001', 'sku': 'foo', 'qty': 10},
{'dept': '002', 'sku': 'bar', 'qty': 20}
]
desired_output=[
{'dept': '001', 'sku': 'foo', 'sold': 100, 'return': 10},
{'dept': '002', 'sku': 'bar', 'sold': 200, 'return': 20},
{'dept': '003', 'sku': 'baz', 'sold': 300, 'return': 0}
]
The code below worked, but is there a more elegant/pythonic way to do this please
merge = []
for s in sold:
found = False
for r in returns:
if (s.get('sku') == r.get('sku') and s.get('dept') == r.get('dept')):
merge.append({'sku': r.get('sku'), 'dept': r.get('dept'), 'sold': s.get('qty'), 'return': r.get('qty')})
found = True
break
if not found:
merge.append({'sku': s.get('sku'), 'dept': s.get('dept'), 'sold': s.get('qty'), 'return': 0})
I have checked this post: How to merge lists of dictionaries, it doesn't give me exactly what I want:
- I need to merge by multiple keys, i.e. sku and dept
- I have to rename the qty to sold and return respectively from 2 lists of dictionaries.
I tried something like below but couldn't get it work:
result = [
s['return'] = r['qty']
for s in sold
for r in return
if s['sku'] == r['sku'] and s['dept'] == r['dept']]
Thanks