Home > Net >  Combining 2D dicts with same key
Combining 2D dicts with same key

Time:04-13

I have created the following list of dictionaries:

[{'A': {'*96': 'Active'}},
{'A': {'*1(ABCD-EFG-SW01-P1)g': 'Active'}},
{'A': {'*65(Interoute-10G-to-AMS)gG': 'Active'}},
{'B': {'*9': 'Active'}},
{'B': {'*10': 'Disabled'}}]

And I would like to turn that into something like this:

{
  'A': {
    '*96': 'Active',
    '*1(ABCD-EFG-SW01-P1)g': 'Active',
    '*65(int-10F-to-ABC)gG': 'Active'
  }
  'B': {
    '*9': 'Active',
    '*10': 'Disabled'
  }
}

I've tried a lot of things but somehow can't seem te figure it out.

Note that I am using Python3.

CodePudding user response:

You can unpack the dictionaries as follows:

raw_dicts = [
    {'A': {'*96': 'Active'}},
    {'A': {'*1(ABCD-EFG-SW01-P1)g': 'Active'}},
    {'A': {'*65(Interoute-10G-to-AMS)gG': 'Active'}},
    {'B': {'*9': 'Active'}},
    {'B': {'*10': 'Disabled'}}
]

dicts = {}
for raw_dict in raw_dicts:
    for key, val in raw_dict.items():
        if key in dicts:
            dicts[key].update(val)
        else:
            dicts[key] = val

CodePudding user response:

quite similar but a bit shorter:

d={}
for i in arr:  # arr - your list
    for k,v in i.items():
        d.setdefault(k,dict()).update(v)

>>> d
'''
{'A': {'*96': 'Active',
       '*1(ABCD-EFG-SW01-P1)g': 'Active',
       '*65(Interoute-10G-to-AMS)gG': 'Active'},
 'B': {'*9': 'Active', 
       '*10': 'Disabled'}}

CodePudding user response:

You need to loop through the raw_dicts and check if "key" is available in your ans. If it's available then use "update" to add sub-dict, else add the new key and set value as value to this key. See this code:

raw_dicts = [
    {'A': {'*96': 'Active'}},
    {'A': {'*1(ABCD-EFG-SW01-P1)g': 'Active'}},
    {'A': {'*65(Interoute-10G-to-AMS)gG': 'Active'}},
    {'B': {'*9': 'Active'}},
    {'B': {'*10': 'Disabled'}}
]

ans = {}
for raw_dict in raw_dicts:
    for key, val in raw_dict.items():
        if key in ans:
            ans[key].update(val)
        else:
            ans[key] = val

print(ans)
  • Related