1 回答

TA貢獻(xiàn)1784條經(jīng)驗 獲得超2個贊
看起來您希望uuid對于相同的“節(jié)點”值是相同的。因此,與其生成它,不如將其存儲到 dict
node_uuids = defaultdict(lambda: uuid.uuid4())
然后,在你的內(nèi)循環(huán)中,而不是
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))
添加回答
舉報