2017-08-10 15 views
-2

私は以下のようなjsonファイルを持っています。 結果辞書には、日付であるキーがあり、各キーには数字キーを持つ別の辞書があります。これらの数字は時間を意味します。 私がしなければならないことは、異なる日付(例:2017-01-02 [4] ['buy'] + 2017-01-01 [4] ['buy'])で同じ数字キーを集めて合計し、購入または販売数の平均を取得します。 私は、これを行う簡単で速い方法があるかどうかを知りたいと思います。Python:値を収集すると、異なる辞書で同じキーが繰り返されます

{ 
    "result": { 
     "2017-01-02": {    
      "4": { 
       "buy": [ 
        2 
       ], 
       "sold": 4 
      }, 
      "5": { 
       "buy": [ 
        1 
       ], 
       "sold": 4 
      }, 
      "6": { 
       "buy": [ 
        67 
       ], 
       "sold": 54 
      } 
     }, 
     "2017-01-01": {     
      "4": { 
       "buy": [ 
        44 
       ], 
       "sold": 8 
      }, 
      "5": { 
       "buy": [ 
        6 
       ], 
       "sold": 14 
      }, 
      "6": { 
       "buy": [ 
        4 
       ], 
       "sold": 67 
      } 
     } 
    } 
} 
+0

「for」ループについて聞いたことがありますか? – Julien

+0

@Ju私はループを知っていて、それを使う方法を知っていますが、同じファイルを1つのファイルにまとめる方法がわかりません。 – ruth

+0

'if'ブロックと' == 'テストについて聞いたことがありますか? – Julien

答えて

0

私はそれを行うには、「シンプルかつ迅速な方法」を考え出すことができませんでしたが、この手続きの方法は、あなたのニーズのために働くことがあります。面倒な部分は、辞書内の値の一部がlist形式(角括弧[]で囲まれています)にあり、その他の部分は単一のintegersです。

これを管理するには、項目値の形式を確認し、listの値にはsum()、整数にはピトンの増分表記(+=)を使用します。

私はコードに他のコメントを含めました。

import json 

with open('data.json', 'r') as f: 
    data = json.load(f) # load json file contents 

buy_total = 0 
sold_total = 0 
buy_count = sold_count = 0. # include `.` for average calculation as decimal 

for date, d in data['result'].iteritems(): 
    for time, v in d.iteritems(): 
     if isinstance(v['buy'], list): # if value is in brackets `[]` 
      buy_count += len(v['buy']) 
      buy_total += sum(v['buy']) 
     elif isinstance(v['buy'], int): # if item is a single integer 
      buy_count += 1 
      sold_total += v['buy'] 
     if isinstance(v['sold'], list): # same as previous if 
      sold_count += len(v['sold']) 
      buy_total += sum(v['sold']) 
     elif isinstance(v['sold'], int): # same as previous elif 
      sold_count += 1 
      sold_total += v['sold'] 

    # optional print formatting 
    # display this date's totals using float format https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points 
    # and string formatting mini-language https://docs.python.org/2/library/string.html#format-specification-mini-language 
    print '{dt}:\n\tbuy total: {bt}\n\tsold total: {st}\n\tbuy average: {b_avg:.2f}\n\tsold average: {s_avg:.2f}\n'.\ 
      format(dt=date, bt=buy_total, st=sold_total, b_avg=buy_total/buy_count, s_avg=sold_total/sold_count) 

    # reset totals for next calculation 
    buy_total = 0 
    sold_total = 0 
    buy_count = sold_count = 0. 

出力:

2017-01-01: 
    buy total: 54 
    sold total: 89 
    buy average: 18.00 
    sold average: 29.67 

2017-01-02: 
    buy total: 70 
    sold total: 62 
    buy average: 23.33 
    sold average: 20.67 

注:計算が正しいように見えるものの、正確性を保証するためにそれらを再度確認してください。

これが役に立ちます。

関連する問題