Search code examples
python-3.xlist-comprehensiondictionary-comprehension

combine a list of dictionaries with one key value match


listofdicts = [
{
    "if-e0": "e0",
    "ip-add-e0": "192.168.1.1",
    "name": "host1"
},
{
    "if-e1": "e1",
    "ip-add-e1": "192.168.2.1",
    "name": "host1"
},
{
    "if-e1": "e1",
    "ip-add-e1": "172.16.1.1",
    "name": "host2"
},
{
    "if-e2": "e2",
    "ip-add-e2": "172.16.2.1",
    "name": "host2"
}]

Expected Result:

listofdicts = [
{
    "if-e0": "e0",
    "ip-add-e0": "192.168.1.1",
    "if-e1": "e1",
    "ip-add-e1": "192.168.2.1",
    "name": "host1"
},
{
    "if-e1": "e1",
    "ip-add-e1": "172.16.1.1",
    "if-e2": "e2",
    "ip-add-e2": "172.16.2.1",
    "name": "host2"
}]

Have been trying to make this work but no luck yet, actual list has more than 60K dicts with unique and matching hosts.

It could be easier to solve but for me, it's been a nightmare from past few hrs.

Appreciate your assistance.

Regards, Avinash


Solution

  • @Kolay.Ne Hi, Hey guys, It did work with a very basic catch. Graph method is fantastic to solve it although I used below approach n that worked:

    for d in listofdicts:
        x = listofdicts.index(d)
        for y in range(len(listofdicts)):
            k = 'name'
            if y != x and y < len(listofdicts):
                if listofdicts[x][k] == listofdicts[y][k]:
                    dc = copy.deepcopy(listofdicts[y])
                    listofdicts[x].update(dc)
                    listofdicts.remove(dc)
    

    Could be other approaches to solve it, im sure pathonic way will be just couple of lines, this solved my problem for the job in hand.

    Thank you to kolay.Ne for responding quickly and trying to assist, and graph method is fantastic as well, requires professional coding and for sure that will be more scalable.