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

时间:2018-11-30 14:47:12

标签: python python-3.x

我试图在'node'值相等时将具有相同id的键uuid.uuid4()添加到内部字典中,并在找到不同的uuid时将其添加到新uuid.uuid4()中。 / p>

假设2个键(在这种情况下为“节点”)具有相同的值,例如-> node:“ Bangalore”,所以我想为其生成相同的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?

1 个答案:

答案 0 :(得分:3)

对于相同的“节点”值,您希望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))