如何合并JSON数组和数组

时间:2019-04-09 14:30:24

标签: python arrays json python-3.x

我有2个数组,如下所示:

数组1:

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

数组2:

[ "A","B"]

我想合并2个数组,我的预期结果是:

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

任何建议都值得赞赏

到目前为止我发现了什么:

1 个答案:

答案 0 :(得分:5)

只需使用list理解:

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)

输出:

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

在评论中提出的情况:

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)

输出:

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