2017-02-17 121 views
-4

我得到了一個json格式的數據。我想從中提取一些有用的數據,所以我需要使用一些循環來完成它。 這裏是我的代碼:創建條件下的字典列表

data=json.loads(res.text) 

for item in data['leagues'][0]['events']: 

    for xx in item['periods']: 

     if 'moneyline' in xx.keys(): 

      md=xx['moneyline'] 

      print(md) 

我得到這樣的:

{'away': 303.0, 'home': 116.0, 'draw': 223.0}

{'away': 1062.0, 'home': -369.0, 'draw': 577.0}

{'away': 337.0, 'home': 109.0, 'draw': 217.0}

{'away': 297.0, 'home': 110.0, 'draw': 244.0}

{'away': 731.0, 'home': -240.0, 'draw': 415.0}

我怎麼能結合這個單獨的數據到一個字典的形式?

我修改我的代碼爲:

data=json.loads(res.text)

dlist=[]

for item in data['leagues'][0]['events']: 
    for xx in item['periods']: 
     if 'moneyline' in xx.keys(): 
       d=xx['moneyline'] 
       dlist.append(d) 
       print(dlist) 

感謝

+2

不要發佈沒有縮進的Python代碼。縮進影響代碼的含義。 – khelwood

+0

請你可以修復問題 – WhatsThePoint

+0

中的代碼我真的很抱歉。 –

回答

0

我建議你使用一個列表中md詞典從xx['moneyline']存儲,並存儲這本字典的密鑰在另一個字典裏,你將存儲所有的值s的md字典。對於每個鍵,列表將這些值存儲在原始md字典中。其結果將是這樣的:

{'home': [116.0, -369.0, 109.0, 110.0, -240.0], 'away': [303.0, 1062.0, 337.0, 297.0, 731.0], 'draw': [223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 223.0, 577.0, 217.0, 244.0, 415.0]} 

第1步:

data=json.loads(res.text) 
list_dictionary = [] #Initialise an empty list to store the dictionaries 
for item in data['leagues'][0]['events']: 
    for xx in item['periods']: 
     if 'moneyline' in xx.keys(): 
      md=xx['moneyline'] 
      list_dictionary.append(md). #Append dictionary item to the list 

第2步:獲取有關md字典中的密鑰的信息,而這些存儲在一個空的字典鍵。爲空字典中的所有鍵初始化一個空列表。

dictionary={} 
for key in md.keys(): 
    dictionary.update({key:[]}) 

步驟3:通過在步驟1中得到的list_dictionary迭代,以及對於在該列表中的每個md詞典,與所有的值更新dictionary

for dict in list_dictionary: 
    for key, value in dict(): 
     dictionary[key].append(value) 

這是如何獲取單個字典中的所有信息,其中鍵與值列表對應。

data=json.loads(res.text) 
list_dictionary = [] #Initialise an empty list to store the dictionaries 
dictionary={} #Initialise an empty dictionary to store all the retrieved data as `md` 
for item in data['leagues'][0]['events']: 
    for xx in item['periods']: 
     if 'moneyline' in xx.keys(): 
      md=xx['moneyline'] 
      list_dictionary.append(md). #Append dictionary item to the list 
      for key in md.keys(): 
       dictionary.update({key:[]}) 

#Store all the `md` values in dictionary as list 
for dict in list_dictionary: 
    for key, value in dict.iteritems(): 
     dictionary[key].append(value) 
+0

非常感謝。但是在'for key'中,值爲dict():' 我得到了「TypeError:'dict'object is not callable」 –

+0

我將代碼的最後一部分修改爲: '對於dict.keys()中的鍵: 對於dict.values()中的值: dictionary [key] .append(value)' 它的工作 –

+0

糟糕,我在該行中犯了一個錯誤。它應該是'dict.iteritems()'中的鍵值,我更新瞭解決方案。 :) –