2017-02-17 123 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()'中的键值,我更新了解决方案。 :) –