Python:从父子映射创建嵌套字典

时间:2015-09-28 09:41:50

标签: python dictionary

我有如下的子父映射:

to go

   let my-list (list 0 1 2 3 0 0 0 8 9 8)
   let length-of-sequence 4
   let number-of-interest 0

   print check-sequence my-list length-of-sequence number-of-interest

end   

to-report check-sequence [a-list sequence number]

  let i 0
  let stopper 0
  let reporter 0

  while [stopper = 0]
  [
    let filtered_sublist filter [? = number] (sublist a-list 0 sequence)    
    if (length filtered_sublist = sequence)
    [ 
      set reporter i
      set stopper 1
    ] 

    set a-list but-first a-list
    set i (i + 1)

    if (length a-list < sequence)
    [
      set stopper 2
    ]
  ]

  ifelse (stopper = 2)
  [ report -1 ]
  [ report reporter ]

end

我想使用上面的方法创建以下嵌套字典:

{4:6,
 6:9,
 7:6,
 5:6,
 8:9,
 11:9,
 10:9,
 12:10,
 13:10}

我能够弄明白我如何能够做到这一点,如果代替将键作为“id”而值为9,6等,我将值作为键。请帮我解决上述格式。

1 个答案:

答案 0 :(得分:0)

我得到了我的查询解决方案。

我将子父映射转换为元组列表,如下所示:

queue_tuples= [(6,9,1),(11,9,1),(8,9,1),(10,9,1),(5,6,2),(7,6,2),(4,6,2),(12,10,2),(13,10,2)]
root = 9

以下是代码:

pGraph = {"id":root,"children":[]}

for tuple in queue_tuples:
    level = tuple[2]
    g = pGraph["children"]
    for i in range(level-1):
        for e in g:
            if tuple[1]==e["id"]:
                g = e["children"]
    flag = 0
    for e in g:
        if tuple[0]==e["id"]:
            flag = 1
            break
    if flag==0:
        g.append({"id":tuple[0],"children":[]})
print pGraph