Reputation: 1065
I have a dictionary like the following -
parent_key : {child : 1, child :2}
I have another dictionary with the same format -
parent_key : {child : 3, child :2}
Both have the same parent key and same child keys.I need to get the output like the following -
parent_key : {{child : 1, child :2},{child : 3, child :2}}
If I use update() method, it simply updates the keys with the latest value but I need in the format I specified. Kindly help!
Upvotes: 0
Views: 215
Reputation: 26315
Your output represents a set of dictionaries:
parent_key : {{child : 1, child :2},{child : 3, child :2}}
which is invalid. I'm also assuming those are not actually duplicate keys and you just replaced every key with child
. Otherwise, the final result is even more invalid, since dictionaries can't have duplicate keys.
Instead, I suggest creating this structure instead:
{parent_key : [{child1 : 1, child2 :2}, {child1 : 3, child2 :2}]}
Which collects each inner child dictionary into a list, which seems to be closest to what you were trying to achieve.
Demo:
from collections import defaultdict
d1 = {"a": {"b": 1, "c": 2}}
d2 = {"a": {"b": 3, "c": 2}}
final_d = defaultdict(list)
for d in (d1, d2):
for k, v in d.items():
final_d[k].append(v)
print(final_d)
# defaultdict(<class 'list'>, {'a': [{'b': 1, 'c': 2}, {'b': 3, 'c': 2}]})
print(dict(d))
# {'a': [{'b': 1, 'c': 2}, {'b': 3, 'c': 2}]}
The above uses a collections.defaultdict
of lists to aggregate the dictionaries into a list.
You could also achieve a nested dictionary result like this:
{parent_key : {child1: [1, 3], child2: [2, 2]}}
Demo:
from collections import defaultdict
d1 = {"a": {"b": 1, "c": 2}}
d2 = {"a": {"b": 3, "c": 2}}
final_d = defaultdict(lambda: defaultdict(list))
for d in (d1, d2):
for k1, v1 in d.items():
for k2, v2 in v1.items():
final_d[k1][k2].append(v2)
print(final_d)
# {'a': defaultdict(<class 'list'>, {'b': [1, 3], 'c': [2, 2]})}
print({k: dict(v) for k, v in final_d.items()})
# {'a': {'b': [1, 3], 'c': [2, 2]}}
Note: defaultdict
is a subclass of dict
, so it acts as a normal dictionary. I've just printed two versions with defaultdict and without for convenience.
Upvotes: 1
Reputation: 141
You can do like this:
dic_arr = [{'a' : 2, 'b' : 4, 'c' : 6},
{'a' : 5, 'b' : 7, 'c' : 8},
{'d' : 10}]
res = {}
for sub in dic_arr:
for key, val in sub.items():
res.setdefault(key, []).append(val)
print(str(res))
Upvotes: 0