当“节点”值相等时,我试图将id具有相同的键添加uuid.uuid4()到内部字典中,并uuid.uuid4()在找到不同的 uuid 时添加一个新键。
假设 2 个键(在本例中为“节点”)具有相同的值,例如 -> 节点:“班加罗尔”,因此我想为其生成相同的 ID,并为每个其他不同的节点生成一个新 ID。
这是我现在正在处理的代码:
import uuid
import json
node_list = [
{
"nodes": [
{
"node": "Kunal",
"label": "PERSON"
},
{
"node": "Bangalore",
"label": "LOC"
}
]
},
{
"nodes": [
{
"node": "John",
"label": "PERSON"
},
{
"node": "Bangalore",
"label": "LOC"
}
]
}
]
for outer_node_dict in node_list:
for inner_dict in outer_node_dict["nodes"]:
inner_dict['id'] = str(uuid.uuid4()) # Remember the key's value here and apply this statement somehow?
print(json.dumps(node_list, indent = True))
这是我想要的回应:
"[
{
"nodes": [
{
"node": "Kunal",
"label": "PERSON",
"id": "fbf094eb-8670-4c31-a641-4cf16c3596d1"
},
{
"node": "Bangalore",
"label": "LOC",
"id": "24867c2a-f66a-4370-8c5d-8af5b9a25675"
}
]
},
{
"nodes": [
{
"node": "John",
"label": "PERSON",
"id": "5eddc375-ed3e-4f6a-81dc-3966590e8f35"
},
{
"node": "Bangalore",
"label": "LOC",
"id": "24867c2a-f66a-4370-8c5d-8af5b9a25675"
}
]
}
]"
但目前它的生成是这样的:
"[
{
"nodes": [
{
"node": "Kunal",
"label": "PERSON",
"id": "3cce6e36-9d1c-4058-a11b-2bcd0da96c83"
},
{
"node": "Bangalore",
"label": "LOC",
"id": "4d860d3b-1835-4816-a372-050c1cc88fbb"
}
]
},
{
"nodes": [
{
"node": "John",
"label": "PERSON",
"id": "67fc9ba9-b591-44d4-a0ae-70503cda9dfe"
},
{
"node": "Bangalore",
"label": "LOC",
"id": "f83025a0-7d8e-4ec8-b4a0-0bced982825f"
}
]
}
]"
如何记住键的值并在字典中为其应用相同的 ID?
一只斗牛犬
相关分类