I'd like to combine the dictionaries if the value value of one key is the same in several dictionaries.

Asked 1 years ago, Updated 1 years ago, 75 views

[{'a': 567.0, 'inventory_code': 'SA100426'}, {'a': 1038.94, 'inventory_code': 'SA100426'}]

In these dictionaries on the list, If the value of the inventory code is the same, I would like to combine the value of a to make it a dictionary.

[{'a': 1605.94, 'inventory_code': 'SA100426'} Like this.

python dictionary list

2022-09-22 18:44

3 Answers

inventory = [{'a': 567.0, 'inventory_code': 'SA100425'}, {
    'a': 1038.94, 'inventory_code': 'SA100426'}, {
    'a': 1038.94, 'inventory_code': 'SA100426'}, {
    'a': 1038.94, 'inventory_code': 'SA100428'}, {
    'a': 1038.94, 'inventory_code': 'SA100426'}]

import itertools

inventory = sorted(inventory, key=lambda x: x['inventory_code'])
for _, v in itertools.groupby(inventory, lambda i:i['inventory_code']):
    items = list(v)
    first_item = items[0]
    first_item['a'] = sum(item['a'] for item in items)
    print(first_item)


{'a': 567.0, 'inventory_code': 'SA100425'}
{'a': 3116.82, 'inventory_code': 'SA100426'}
{'a': 1038.94, 'inventory_code': 'SA100428'}


2022-09-22 18:44

Try the itertools module.

The groupby function brings together the same adjacent things.

inventory = [{'a': 567.0, 'inventory_code': 'SA100425'}, {
    'a': 1038.94, 'inventory_code': 'SA100426'}, {
    'a': 1038.94, 'inventory_code': 'SA100426'}, {
    'a': 1038.94, 'inventory_code': 'SA100428'}, {
    'a': 1038.94, 'inventory_code': 'SA100426'}]

import itertools

inventory = sorted (inventory, key=lambdax: x['inventory_code']) # Sort and arrange the same things together.
For i, vinitertools.groupby (inventory, lambda i:i['inventory_code']): #Inventory_code to bind the same things together.
    print(list(v))


[{'a': 567.0, 'inventory_code': 'SA100425'}]
[{'a': 1038.94, 'inventory_code': 'SA100426'}, {'a': 1038.94, 'inventory_code': 'SA100426'}, {'a': 1038.94, 'inventory_code': 'SA100426'}]
[{'a': 1038.94, 'inventory_code': 'SA100428'}]


2022-09-22 18:44

The problem you requested was not read properly. Created code again. I hope you'll be of course.I modified the inventory a bit. It won't be a problem, though. For your information, the code you posted at the beginning is completely wrong.

from collections import defaultdict
inventory = [{'code': 25, 'amt': 3300}, {
    'code': 26, 'amt': 2990}, {'code': 26, 'amt': 1290}, {'code': 28, 'amt': 1990}, {'code': 26, 'amt': 3350}]

c = defaultdict(int)

for d in inventory:
    c[d['code']] += d['amt']

new_inventory = [{'code': code, 'amt': amt} for code, amt in c.items()]
print(new_inventory)


2022-09-22 18:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.