0

How can I turn the following list:

[{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}]

into

[{'xx1' : {'test1': 8, 'test3':2}, 'yy2' : {'test1': 5, 'test5': 6}}]

What is the syntactically cleanest way to accomplish this? Or, how can it be done by using reduce()?

Thanks for any help!!

retr0327
  • 141
  • 4
  • 9
  • 1
    Does this answer your question? [How to merge dictionaries of dictionaries?](https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries) – Jan Wilamowski Sep 28 '21 at 08:27

1 Answers1

0

something like the below

from collections import defaultdict

data = defaultdict(dict)
lst = [{'xx1': {'test1': 8}}, {'xx1': {'test3': 2}}, {'yy2': {'test1': 5}}, {'yy2': {'test5': 6}}]

for entry in lst:
    for k, v in entry.items():
        kk, vv = next(iter(v.items()))
        data[k][kk] = vv
print(data)

output

defaultdict(<class 'dict'>, {'xx1': {'test1': 8, 'test3': 2}, 'yy2': {'test1': 5, 'test5': 6}})
balderman
  • 22,927
  • 7
  • 34
  • 52