2017-02-17 11 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}

私が辞書形式にこの別のデータを組み合わせることができますどのように?

+2

インデントなしでPythonコードを投稿しないでください。インデントはコードの意味に影響します。 – khelwood

+0

質問にあるコードを修正してください。 – WhatsThePoint

+0

本当にすみません。 –

答えて

0

私はあなたがxx['moneyline']からmd辞書を保存するために、リストを使用することをお勧めし、保存

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) 

ありがとう:

私はに私のコードを変更しますこの辞書のキーを別の辞書に入れて、すべての値を保存します辞書の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) 

これは、キーが値のリストに対応する1つの辞書内のすべての情報を取得する方法です。

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

ありがとうございました。 "TypeError: 'dict'オブジェクトは呼び出し可能ではありません" –

+0

私はあなたのコードの最後の部分を次のように変更します: 'for key in dict.keys(): dict.values()の値: 辞書[キー] .append(値) ' それは動作します –

+0

私はその行に誤りを犯しました。これは、 'dict.iteritems()のキー、値のために'あったはずです。私は解決策を更新しました。 :) –

関連する問題