gpt4 book ai didi

python - 将项目添加到字典列表中具有相同值的字典

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:35 25 4
gpt4 key购买 nike

我正在尝试在“节点”值相等时将具有相同 uuid.uuid4() 的键 id 添加到内部字典中,并且添加一个新的 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"
}
]
}
]"

如何记住key的值并在字典中应用相同的ID?

最佳答案

对于相同的“节点”值,您似乎希望 uuid 相同。所以,不是生成它,而是将它存储到字典中

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))

关于python - 将项目添加到字典列表中具有相同值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53559743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com