Home > Software engineering >  merge dicts that have the same value for specific key
merge dicts that have the same value for specific key

Time:04-27

I need to combine dictionaries that have the same value for the key "tag".

Like from this:

[
    [
        {
            "tag": "#2C00L02RU",
            "stamina": 233
        },
        {
            "tag": "#8YG8RJV90",
            "stamina": 20
        },
        {
            "tag": "#LQV2JCPR",
            "stamina": 154
        },
        {
            "tag": "#9JQLPGLJJ",
            "stamina": 134
        }
    ],
    [
        {
            "tag": "#2C00L02RU",
            "health": 200
        },
        {
            "tag": "#8YG8RJV90",
            "health": 40
        },
        {
            "tag": "#LQV2JCPR",
            "health": 100
        },
        {
            "tag": "#9JQLPGLJJ",
            "health": 240
        }
    ],
    [
        {
            "tag": "#LQV2JCPR",
            "fame": 1
        },
        {
            "tag": "#8YG8RJV90",
            "fame": 2
        },
        {
            "tag": "#9JQLPGLJJ",
            "fame": 3
        },
        {
            "tag": "#2C00L02RU",
            "fame": 4
        }
    ],
    [
        {
            "tag": "#LQV2JCPR",
            "moves": 6
        },
        {
            "tag": "#8YG8RJV90",
            "moves": 0
        },
        {
            "tag": "#9JQLPGLJJ",
            "moves": 8
        },
        {
            "tag": "#2C00L02RU",
            "moves": 4
        }
    ]
]

to this:

[
    {
        "tag": "#2C00L02RU",
        "stamina": 233,
        "health": 200,
        "fame": 4,
        "moves": 4
    },
    {
        "tag": "#8YG8RJV90",
        "stamina": 20,
        "health": 40,
        "fame": 2,
        "moves": 2
    },
    {
        "tag": "#LQV2JCPR",
        "stamina": 154,
        "health": 100,
        "fame": 1,
        "moves": 6
    },
    {
        "tag": "#9JQLPGLJJ",
        "stamina": 134,
        "health": 240,
        "fame": 3,
        "moves": 8
    }
]

I've already tried iterating through countless loops, but only got failures. I won't show any of my attempts here because they didn't even come close to the expected result.

If you need any other information, just let me know.

CodePudding user response:

If lst is list from your question, you can do:

out = {}
for l in lst:
    for d in l:
        out.setdefault(d["tag"], {}).update(d)

print(list(out.values()))

Prints:

[
    {"tag": "#2C00L02RU", "stamina": 233, "health": 200, "fame": 4, "moves": 4},
    {"tag": "#8YG8RJV90", "stamina": 20, "health": 40, "fame": 2, "moves": 0},
    {"tag": "#LQV2JCPR", "stamina": 154, "health": 100, "fame": 1, "moves": 6},
    {"tag": "#9JQLPGLJJ", "stamina": 134, "health": 240, "fame": 3, "moves": 8},
]
  • Related