1 回答

TA贡献1784条经验 获得超2个赞
看起来您希望uuid对于相同的“节点”值是相同的。因此,与其生成它,不如将其存储到 dict
node_uuids = defaultdict(lambda: uuid.uuid4())
然后,在你的内循环中,而不是
inner_dict['id'] = str(uuid.uuid4())
你写
inner_dict['id'] = node_uuids[inner_dict['node']]
一个完整的工作示例如下:
from collections import defaultdict
import uuid
import json
node_list = [
{
"nodes": [
{
"node": "Kunal",
"label": "PERSON"
},
{
"node": "Bangalore",
"label": "LOC"
}
]
},
{
"nodes": [
{
"node": "John",
"label": "PERSON"
},
{
"node": "Bangalore",
"label": "LOC"
}
]
}
]
node_uuids = defaultdict(lambda: uuid.uuid4())
for outer_node_dict in node_list:
for inner_dict in outer_node_dict["nodes"]:
inner_dict['id'] = str(node_uuids[inner_dict['node']])
print(json.dumps(node_list, indent = True))
添加回答
举报