2017-06-22 105 views
0

我有一個包含多個鍵和值的字典,其值也包含鍵值對。我沒有得到如何創建在python中使用這個字典的動態json。這裏的字典:在python中創建動態json對象

image_dict = {"IMAGE_1":{"img0":"IMAGE_2","img1":"IMAGE_3","img2":"IMAGE_4"},"IMAGE_2":{"img0":"IMAGE_1", "img1" : "IMAGE_3"},"IMAGE_3":{"img0":"IMAGE_1", "img1":"IMAGE_2"},"IMAGE_4":{"img0":"IMAGE_1"}} 

我預期的結果是這樣的:

{ 
    "data": [ 
    { 
     "image": { 
     "imageId": { 
      "id": "IMAGE_1" 
     }, 
     "link": { 
      "target": { 
      "id": "IMAGE_2" 
      }, 
      "target": { 
      "id": "IMAGE_3" 
      }, 
      "target": { 
      "id": "IMAGE_4" 
      } 
     } 
     }, 
     "updateData": "link" 
    }, 
     { 
     "image": { 
     "imageId": { 
      "id": "IMAGE_2" 
     }, 
     "link": { 
      "target": { 
      "id": "IMAGE_1" 
      }, 
      "target": { 
      "id": "IMAGE_3" 
      } 
     } 
     }, 
     "updateData": "link" 
    }, 
    { 
     "image": { 
     "imageId": { 
      "id": "IMAGE_3" 
     }, 
     "link": { 
      "target": { 
      "id": "IMAGE_1" 
      }, 
      "target": { 
      "id": "IMAGE_2" 
      } 
     } 
     }, 
     "updateData": "link" 
    } , 
    { 
     "image": { 
     "imageId": { 
      "id": "IMAGE_4" 
     }, 
     "link": { 
      "target": { 
      "id": "IMAGE_1" 
      } 
     } 
     }, 
     "updateData": "link" 
    } 
    ] 
} 

我試圖解決這個問題,但我沒有得到預期的結果。

result = {"data":[]} 

for k,v in sorted(image_dict.items()): 
    for a in sorted(v.values()): 
     result["data"].append({"image":{"imageId":{"id": k}, 
             "link":{"target":{"id": a}}},"updateData": "link"}) 
print(json.dumps(result, indent=4)) 
+0

的'json'部分是完全(當然,大部分)在這裏無關,你的問題是「怎麼辦我將這個源詞典轉換爲目標字典 –

+0

是的,你的權利@brunodesthuilliers –

+0

@rajendrapawar,你的預期的json是無效的在一個dict「..」鏈接中不能有重複的鍵:{ 「target」:{ 「ID」: 「IMAGE_2」 }, 「目標」:{ 「ID」: 「IMAGE_3」 }, 「目標」:{ 「ID」: 「IMAGE_4」 } ..' – RomanPerekhrest

回答

0

在Python字典中,您不能使用相同的鍵具有2個值。所以你不能有多個目標被稱爲「目標」。所以你可以索引它們。此外,我不知道這是什麼問題,有動態對象做,但這裏是我得到了工作代碼:

import re 
dict_res = {} 
ind = 0 
for image in image_dict: 
    lin_ind = 0 
    sub_dict = {'image' + str(ind): {'imageId': {image}, 'link': {}}} 
    for sub in image_dict[image].values(): 
     sub_dict['image' + str(ind)]['link'].update({'target' + str(lin_ind): {'id': sub}}) 
     lin_ind += 1 
    dict_res.update(sub_dict) 
    ind += 1 
dict_res = re.sub('target\d', 'target', re.sub('image\d', 'image', str(dict_res))) 
print dict_res 
+0

這是什麼不同於索引號? – cookiedough

+0

你可以把它變成一個字符串。並使用re函數。我對代碼做了編輯,爲你做了這個。 – cookiedough