首页 > 解决方案 > 操作两个 JSON 列表并更新它们的有效方法

问题描述

我想对包含 JSON 的 python 列表进行操作,使得 in 的keysource_split_response被替换为namewhere online_sourcevalueonlineId等于keyin 的值source_split_response

online_source = [{'_id': {'$oid': '5c989c112ae8570ca8c6bcd1'},
  'name': 'Blogs',
  'onlineId': '606881',
  'type': 'source'},
 {'_id': {'$oid': '5c989c122ae8570ca8c6bcd2'},
  'name': 'Facebook',
  'onlineId': '606911',
  'type': 'source'},
 {'_id': {'$oid': '5c989c122ae8570ca8c6bcd3'},
  'name': 'Instagram',
  'onlineId': '606937',
  'type': 'source'},
 {'_id': {'$oid': '5c989c122ae8570ca8c6bcd4'},
  'name': 'Tumblr',
  'onlineId': '606961',
  'type': 'source'},
 {'_id': {'$oid': '5c989c122ae8570ca8c6bcd5'},
  'name': 'Twitter',
  'onlineId': '606963',
  'type': 'source'},
 {'_id': {'$oid': '5c989c132ae8570ca8c6bcd6'},
  'name': 'Others',
  'onlineId': '606949',
  'type': 'source'},
 {'_id': {'$oid': '5c989c132ae8570ca8c6bcd7'},
  'name': 'Forums',
  'onlineId': '606925',
  'type': 'source'},
 {'_id': {'$oid': '5c989c132ae8570ca8c6bcd8'},
  'name': 'Youtube',
  'onlineId': '606965',
  'type': 'source'}]


source_split_response = [
        {
            "key" : "News", 
            "doc_count" : 20
        }, 
        {
            "key" : "606881",
            "doc_count" : 12
        }, 
        {
            "key" : "606925", 
            "doc_count" : 6
        }
    ]

Python代码:

for ind_source_resp in range(0, len(source_split_response)):
    for ind_source_map in range(0, len(online_source)):
        if(source_split_response[ind_source_resp]['key'] == online_source[ind_source_map]['onlineId']):
            source_split_response[ind_source_resp]['key'] = online_source[ind_source_map]['name']
print(source_split_response)

印刷:[{'key': 'News', 'doc_count': 20}, {'key': 'Blogs', 'doc_count': 12}, {'key': 'Forums', 'doc_count': 6}]

预期输出:[{'key': 'News', 'doc_count': 20}, {'key': 'Blogs', 'doc_count': 12}, {'key': 'Forums', 'doc_count': 6}]

虽然我得到了所需的最终输出,但它们是一种更有效和更pythonic的方式来实现相同的目标吗?

标签: pythonjsonlistdictionaryoptimization

解决方案


您可以将 id 映射到字典中的名称,以避免迭代整个数组以匹配它们:

idDict = dict()

for entry in online_source:
    idDict[entry['onlineId']] = entry['name']

for entry in source_split_response:
    if entry['key'] in idDict:
        entry['key'] = idDict[entry['key']]

print(source_split_response)

我不知道你为什么想要列表理解,但这里有一种方法:

idDict = {entry['onlineId']:entry['name'] for entry in online_source}

[entry.update({'key': idDict.get(entry['key'], entry['key'])}) for entry in source_split_response]

print(source_split_response)

推荐阅读