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

当“节点”值相等时,我试图将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?


SMILET
浏览 169回答 1
1回答

一只斗牛犬

看起来您希望uuid对于相同的“节点”值是相同的。因此,与其生成它,不如将其存储到 dictnode_uuids = defaultdict(lambda: uuid.uuid4())然后,在你的内循环中,而不是inner_dict['id'] = str(uuid.uuid4())你写inner_dict['id'] = node_uuids[inner_dict['node']]一个完整的工作示例如下:from collections import defaultdictimport uuidimport jsonnode_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))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python