0

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'}]
groutch
  • 3
  • 2
  • Are list items matched positionally, or on the value of the dictionary key `x`? Have you tried something yet yourself that we might use as a stepping stone? – JonSG Jan 20 '23 at 13:58
  • @JonSG on the value of the dictionary key x – groutch Jan 20 '23 at 14:09
  • 1
    u re right, selected answer in not correct – groutch Jan 20 '23 at 14:16
  • Does this answer your question? [join two lists of dictionaries on a single key](https://stackoverflow.com/questions/5501810/join-two-lists-of-dictionaries-on-a-single-key) – JonSG Jan 20 '23 at 14:22

1 Answers1

2

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())
Bharel
  • 23,672
  • 5
  • 40
  • 80