2016-06-10 45 views
0

我有元組的列表,並希望從中從一個元組和按鍵的單獨列表值的列表創建一個JSON字典

[(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C'), (4, 'd', 'D'), (5, 'e', 'E'), (6, 'f', 'F'), (7, 'g', 'G'), (8, 'h', 'H'), (9, 'i', 'I')] 

和預期JSON使JSON

{ 
    "List": [ 
       { 
        "name": "1", 
        "description": "a", 
        "type": "A" 
       }, 
       { 
        "name": "2", 
        "description": "b", 
        "type": "B" 
       }, 
       { 
        "name": "3", 
        "description": "c", 
        "type": "C" 
       }, 
       and so on.... 
      ] 
} 

我該怎麼做?

重複的確定的答案沒有工作,給了這個錯誤

ValueError: dictionary update sequence element #0 has length 3; 2 is required 
+0

[從元組列表中格式化JSON字符串的更多pythonic方法]的可能重複(http://stackoverflow.com/questions/13761054/mo​​re-pythonic-way-to-format-a-json-string-from-元組列表) – Serenity

+0

沒有工作,給出了錯誤ValueError:字典更新序列元素#0的長度爲3; 2是必需的 – x0v

+0

他可能只是讀你的標題,這聽起來像你想要做的是提名的副本。我會爲你編輯你的標題。 – tripleee

回答

2

zip按鍵和各元組調用字典的結果,那麼json.dumps

import json 
keys = ["name", "description","type"] 

l=[(1, 'a', 'A'), (2, 'b', 'B'), (3, 'c', 'C'), (4, 'd', 'D'), (5, 'e', 'E'), (6, 'f', 'F'), (7, 'g', 'G'), (8, 'h', 'H'), (9, 'i', 'I')] 


js = json.dumps({"List":[dict(zip(keys, tup)) for tup in l]}) 

它給你:

'{"List": [{"type": "A", "name": 1, "description": "a"}, {"type": "B", "name": 2, "description": "b"}, {"type": "C", "name": 3, "description": "c"}, {"type": "D", "name": 4, "description": "d"}, {"type": "E", "name": 5, "description": "e"}, {"type": "F", "name": 6, "description": "f"}, {"type": "G", "name": 7, "description": "g"}, {"type": "H", "name": 8, "description": "h"}, {"type": "I", "name": 9, "description": "i"}]}' 
+0

非常感謝,但我認爲OrderedDict會對我更好。反正再次感謝 – x0v

相關問題