我有以下两个数据集,我希望以一种非常具体的方式合并它们:
stream = {
"sdd": [{
"eid": "e532fcdb-2f3f-4c51-9afb-996b8679a5da",
"nid": "ebef3cb1-9053-4d1e-b409-b682236445b7",
"nname": "client"
}, {
"eid": "901b51b1-851f-448e-b2cc-9730267f824b",
"nid": "0b5d79b5-0d21-4186-b3db-8f4a9f2b25fb",
"nname": "server"
}]
}
概要文件
profile = [{
"ackid": "5dfe5dd4-e863-4474-bdad-54231b925f12",
"nid": "ebef3cb1-9053-4d1e-b409-b682236445b7",
"name": "default",
"resources": {
"cpu": {
"min_cores": "2",
"max_cores": "8"
},
"memory": {
"min": "2000",
"max": "10000"
},
"storage": {
"min": "50",
"max": "100"
}
}
}]
我想做的是添加到'流'从'配置文件'的匹配(最小)值从'资源',其中'nid'匹配得到这样的东西:
{
"sdd": [{
"eid": "e532fcdb-2f3f-4c51-9afb-996b8679a5da",
"nid": "ebef3cb1-9053-4d1e-b409-b682236445b7",
"nname": "client",
"cpu": "2",
"mem": "2000",
"storage":"50"
}, {
"eid": "901b51b1-851f-448e-b2cc-9730267f824b",
"nid": "0b5d79b5-0d21-4186-b3db-8f4a9f2b25fb",
"nname": "server"
}]
}
def get_dict(x):
return {'min':x['memory']['min'], 'cpu':x['cpu']['min_cores'],
'storage':x['storage']['min']}
Out = {'ssd':[i|get_dict(j['resources']) if i['nid']==j['nid'] else i for i in
stream['sdd'] for j in profile]}
Out:
{'ssd': [{'eid': 'e532fcdb-2f3f-4c51-9afb-996b8679a5da',
'nid': 'ebef3cb1-9053-4d1e-b409-b682236445b7',
'nname': 'client',
'min': '2000',
'cpu': '2',
'storage': '50'},
{'eid': '901b51b1-851f-448e-b2cc-9730267f824b',
'nid': '0b5d79b5-0d21-4186-b3db-8f4a9f2b25fb',
'nname': 'server'}]}
尝试:
tmp = {}
for p in profile:
tmp[p["nid"]] = {
"cpu": p["resources"]["cpu"]["min_cores"],
"memory": p["resources"]["memory"]["min"],
"storage": p["resources"]["storage"]["min"],
}
out = {}
for k, v in stream.items():
out[k] = [{**i, **tmp.get(i["nid"], {})} for i in v]
print(out)
打印:
{
"sdd": [
{
"eid": "e532fcdb-2f3f-4c51-9afb-996b8679a5da",
"nid": "ebef3cb1-9053-4d1e-b409-b682236445b7",
"nname": "client",
"cpu": "2",
"memory": "2000",
"storage": "50",
},
{
"eid": "901b51b1-851f-448e-b2cc-9730267f824b",
"nid": "0b5d79b5-0d21-4186-b3db-8f4a9f2b25fb",
"nname": "server",
},
]
}