python - 操作两个 JSON 列表并更新它们的有效方法
问题描述
我想对包含 JSON 的 python 列表进行操作,使得 in 的key
值source_split_response
被替换为name
where online_source
valueonlineId
等于key
in 的值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的方式来实现相同的目标吗?
解决方案
您可以将 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)
推荐阅读
- python - 在字符串中查找单词,然后在 excel 中写入字符串,找到不同字体的单词
- android - @Override "Method..." 从另一个项目复制方法后
- javascript - 如何在 vue JavaScript 中将数据从一个组件恢复到另一个组件
- python - Python:如何在 Pandas 的循环中正确使用滚动平均值?
- r - 使用 tufte-book 在 bookdown 中设置 PDF 输出的纸张大小
- css - 对话框、快餐栏、...entryComponents 上的 Angular Material 自定义主题
- r - 在 R 中生成特殊矩阵的更有效函数
- sql - SQL罗斯文数据库查询重复行
- google-apps-script - 如何创建一个接受多个输入的谷歌脚本提示
- r - R 包在 Windows 上构建,但无法运行示例 - 使 R 会话崩溃