【问题标题】:python : gathering values has same key in different dictionaries while iteratingpython:在迭代时收集值在不同字典中具有相同的键
【发布时间】:2023-03-06 10:23:01
【问题描述】:

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

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

【问题讨论】:

  • 你听说过for循环吗?
  • @Ju 我知道 for 循环并且知道如何使用它,但我不知道如何在一个文件中细化相同的键
  • 你听说过if 块和== 测试吗?

标签: python loops dictionary sum


【解决方案1】:

我想不出一个“简单而快速的方法”来做到这一点,但这种程序性的方法可能会满足您的需求。棘手的部分似乎是字典中的某些值是list 格式(用括号括起来[]),而其他值是单个integers

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

我在代码中包含了其他 cmets。

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

注意:虽然计算看起来正确,但请再次检查以确保准确性。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2014-04-27
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    相关资源
    最近更新 更多