1

I have 2 arrays as below:

array 1:

[
    {"name": "A", "class" : "1"},
    {"name": "B", "class" : "2"},
    {"name": "C", "class" : "3"}
]

array 2:

[ "A","B"]

I wanna merge 2 arrays, and my expected result:

[
    {"name": "A", "class" : "1"},
    {"name": "B", "class" : "2"}
]

Any suggestion is appreciated

What I found so far:

4
  • Possible duplicate of Python: filter list of list with another list Commented Apr 9, 2019 at 14:35
  • This question doesn't seem to be related to JSON, unless you are getting these values as a string. Your first value is just a normal Python dictionary. Commented Apr 9, 2019 at 14:37
  • This isn't a merge; it's a filter. You want to select the dicts whose name value appears in list 2. JSON is irrelevant, except as the source of one or both lists; the filtering doesn't care how the lists get defined. Commented Apr 9, 2019 at 14:39
  • @chepner I took it as a "merge" in the SQL sense. Commented Apr 9, 2019 at 14:41

1 Answer 1

5

Just use a list comprehension:

first = [
         {"name": "A", "class" : "1"},
         {"name": "B", "class" : "2"},
         {"name": "C", "class" : "3"}
]

second = ['A', 'B']

result = [d for d in first if d['name'] in second]
print(result)

Output:

[{'name': 'A', 'class': '1'}, {'name': 'B', 'class': '2'}]

In the case raised in the comments:

from operator import itemgetter

first = [
         {"name": "A", "class" : "1"},
         {"name": "B", "class" : "2"},
         {"name": "C", "class" : "3"}
]

second = [
         {"name": "A"},
         {"name": "B"}
]

result = [d for d in first if d['name'] in map(itemgetter('name'), second)]
print(result)

Output:

[{'name': 'A', 'class': '1'}, {'name': 'B', 'class': '2'}]
Sign up to request clarification or add additional context in comments.

7 Comments

if the 2nd array is a JSON array : [{'name': 'A'}, {'name':'B'}]. How to achieve the result ?
@PhongVu [d for d in first if d in second] will work fine.
@PhongVu A JSON array is just a string that can be decoded into some native data structure. [{'name': 'A'}, {'name':'B'}] is an ordinary Python list consisting of dicts that was initialized from a JSON array.
Thanks @chepner for making clear the word "JSON array"
@gmds: I tried your suggestion, it just returns an empty array []
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.