2017-02-09 48 views
0

我現在做一個API調用蒸汽的Web API,它得到一個JSON響應,看起來像這樣:Python的創建JSON字典值

{ 
"response": { 
    "globalstats": { 
     "heist_success": { 
      "total": "58932654920", 
      "history": [ 
       { 
        "date": 1486252800, 
        "total": "696574" 
       }, 
       { 
        "date": 1486339200, 
        "total": "357344" 
       }, 
       { 
        "date": 1486425600, 
        "total": "356800" 
       }, 
       { 
        "date": 1486512000, 
        "total": "311056" 
       } 
      ] 

     } 
    }, 
    "result": 1 
} 

的日期是在UNIX時間戳和總的量。我想要做的是從日期和時間的值中創建一個字典,而不是名稱。我嘗試使用以下內容:

dict = dict(data['response']['globalstats']['heist_success']['history']) 

但是,這只是創建了「date」「total」的字典。

我該如何創建一個只有值的字典?

+0

爲了清晰起見,我想創建一個帶有第一列中的時間戳和第二列中的數量的字典。 –

+1

將時間戳*作爲關鍵字*並將金額*作爲值* ...? – deceze

回答

5

你可能得到的值,使詞典出來,

這是你可以做的

代碼

d = data['response']['globalstats']['heist_success']['history'] 
result_dict = dict((i["date"],i["total"]) for i in d) 

你也可以使用dict comprehension如果使用Python版本什麼2.7或以上

result_dict = {i["date"]:i["total"] for i in d} 

輸出

{1486252800: '696574', 
1486339200: '357344', 
1486425600: '356800', 
1486512000: '311056'} 
+0

完美!像魅力一樣工作。謝謝您的幫助! –

+0

對不起,但我不能,因爲我得到不到15代表自己:/ –

+0

沒有看到...完成! –

2

您可以使用字典理解:

D = {h['date']:h['total'] for h in data['response']['globalstats']['heist_success']['history']} 

for將遍歷的歷史和日期,總http://stardict.sourceforge.net/Dictionaries.php下載的列表中選擇鍵和值。