python:在迭代时,收集值在不同的字典中具有相同的键

时间:2017-08-10 00:58:32

标签: python loops dictionary sum

我有一个json文件,如下所示。 在结果字典中,有一些键是日期,每个键都有另一个具有数字键的字典。这些数字意味着时间。 我要做的是在不同的日期收集相同的数字键(例如:2017-01-02 [4] ['购买'] + 2017-01-01 [4] ['购买&# 39;])并将其求和,得到买入或卖出的平均值。 我想知道是否有简单快捷的方法来做到这一点。

{
  "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
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我无法想出一个“简单快捷的方法”,但这种程序方式可能适合您的需求。棘手的部分似乎是字典中的某些值采用list格式(括号[]包围),其他值为单integers

因此,为了管理这一点,我们可以检查项值的格式,并使用sum()表示list值,或使用pythons增量表示法(+=)表示整数。 / p>

我在代码中包含了其他评论。

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

注意:虽然计算结果似乎正确,但请再次检查以确保准确性。

希望这有帮助。