Home > OS >  python duplicate values and key ​in multiple dictionary rearrange into single dictionary
python duplicate values and key ​in multiple dictionary rearrange into single dictionary

Time:07-11

i have a list of dict like this

list_1 = [{'id': '123', 'name': {'new': 'kevin'}},

          {'id': '123', 'name': {'old': 'alan'}},

         {'id': '456', 'name': {'new': 'jason'}},

          {'id': '456', 'name': {'old': 'jack'}}]

But I want to merge the same values ​​together using something function

The desired output is as follows

list_1 = somethingfunction()

output:

{'id': '123', 'name': {'new': 'kevin','old': 'alan'}}

{'id': '456', 'name': {'new': 'jason','old': 'jack'}}

Don't know if there is any function that can quickly merge the same values and key ​​together

CodePudding user response:

Looks like you're looking for something like this:

from collections import defaultdict
from pprint import pprint


def merge_group(group: list[dict]) -> dict:
    """
    Merge a group of dicts into a single dict.

    First-level nested dicts are merged, other values replace previous values.
    """
    output = None
    for item in group:
        if output is None:
            # First item, (shallow-)copy it as-is.
            output = item.copy()
            continue
        for key, value in item.items():
            if isinstance(value, dict):  # merge nested dicts (one level deep)
                output[key].update(value)
            else:  # replace other values
                output[key] = value
    return output


def merge_by_key(input: list[dict], key: str, group_merger=merge_group) -> list[dict]:
    """
    Group a list of dicts given a key, then merge the groups using the group_merger function.
    """
    groups = defaultdict(list)
    for item in input:
        groups[item[key]].append(item)
    return [group_merger(group) for group in groups.values()]


list_1 = [
    {"id": "123", "name": {"new": "kevin"}},
    {"id": "123", "name": {"old": "alan"}, "color": "purple"},
    {"id": "456", "name": {"new": "jason"}},
    {"id": "456", "name": {"old": "jack"}},
]
pprint(merge_by_key(list_1, "id"))

The output is

[
  {'color': 'purple', 'id': '123', 'name': {'new': 'kevin', 'old': 'alan'}},
  {'id': '456', 'name': {'new': 'jason', 'old': 'jack'}}
]

CodePudding user response:

Code

def merge_groups(lst):
    result = {}
    for d in list_1:
        result.setdefault(d['id'], {})           # dictionary with id (if doesn't exists)
        result[d['id']].update({"id": d["id"]})  # add 'id' key value pairs
        result[d['id']].update(d['name'])        # add 'name' key, value pairs

    return list(result.values())

print(merge_groups(list_1))

Output

[{'id': '123', 'new': 'kevin', 'old': 'alan'},
 {'id': '456', 'new': 'jason', 'old': 'jack'}]
  • Related