我有两个json对象,如果特定键在两者之间匹配,我想扩展一个来包含另一个的值。
我通过这个完成了它:
import json
data = json.loads('{"docs": [{"type": "D", "status": "P", "payment": "P", "value": 176843, "baseId": "0112200196032", "declId": 305724174}, {"type": "D", "status": "P", "payment": "P", "value": 17843, "baseId": "0112190348102"}]}')
comps = json.loads('{"docs": [{"date": "2018-02-14", "baseId": 112200196032, "declId": 305724174}, {"date": "2017-11-13", "baseId": 112190348102, "declId": 299361504}, {"date": "2017-08-05", "baseId": 112178876161, "declId": 293267255}]}')
for dec in data['docs']:
for com in comps['docs']:
if int(dec['baseId']) == int(com['baseId']):
dec['declId'] = com['declId']
print(data)
输出:
{
'docs':[
{
'type':'D',
'status':'P',
'payment':'P',
'value':176843,
'baseId':'0112200196032',
'declId':305724174
},
{
'type':'D',
'status':'P',
'payment':'P',
'value':17843,
'baseId':'0112190348102',
'declId':299361504
}
]
}
我真的需要使用嵌套的for循环吗?可以更有效地完成吗? List / Dict理解?
答案 0 :(得分:0)
无论应该在此处执行多少异常处理,您的代码实际上都非常易读,并且被认为是解决此问题的好方法。但是,如果要优化代码,则应指定真正的优化范围,即是否为运行时内存优化。如果问题是运行时间,您可以从comps
创建一个字典,其格式为键值为baseId
,值为整个字典,那么您可以这样做:
for dec in data['docs']:
try:
val = comps[dec['baseId']]
except KeyError:
pass
else:
dec['declId'] = val['declId']