Home > Blockchain >  Array of dict to dict
Array of dict to dict

Time:01-20

I have arrays

first = [{'x': 'name1', 'a': '333'}, {'x': 'name2', 'a': '234'}, {'x': 'name3', 'a': '432'}, {'x': 'name4', 'a': '943'}, {'x': 'name5', 'a': '643'}]
second = [{'x': 'name1', 'b': '1333'}, {'x': 'name2', 'b': '1234'}, {'x': 'name3', 'b': '1432'}, {'x': 'name4', 'b': '1943'}]

What function can i use to get this result:

[{'x': 'name1', 'b': '1333', 'a': '333'}, {'x': 'name2', 'b': '1234', 'a': '234'}, {'x': 'name3', 'b': '1432', 'a': '432'}, {'x': 'name4', 'b': '1943', 'a': '943'}, {'x': 'name5', 'b': None, 'a': '643'}]

CodePudding user response:

You can simply combine the dictionaries using | like so:

result = [f | s for f, s in zip(first, second)]

Based on your edited question, matching on x:

from collections import defaultdict
from functools import partial
from itertools import chain
# Each dict starts with defaults a, b == None
merged = defaultdict(partial(dict.fromkeys, ("a", "b")))

# Merge all dictionaries
for dict_ in chain(first, second):
    merged[dict_["x"]].update(dict_)

# Get the merged dicts
result = list(merged.values())
  • Related