Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 函数聚合一组数据并输出嵌套字典_Python_Python 2.7_Recursion_Defaultdict - Fatal编程技术网

Python 函数聚合一组数据并输出嵌套字典

Python 函数聚合一组数据并输出嵌套字典,python,python-2.7,recursion,defaultdict,Python,Python 2.7,Recursion,Defaultdict,我已经到处寻找这个问题的解决方案,但我找不到任何我正在努力实现的方法 我想创建一个有三个参数的Python函数 data_对象-这是一个字典列表,其中每个字典都有相同的字段-从1-n个要分组的“维度”字段到1-n个要聚合的度量字段 维度-要按其分组的维度字段列表 metrics—要聚合的度量字段列表 我以前解决此问题的方法是使用setdefault: struc = {} for row in rows: year = row['year'] month = row['month

我已经到处寻找这个问题的解决方案,但我找不到任何我正在努力实现的方法

我想创建一个有三个参数的Python函数

  • data_对象-这是一个字典列表,其中每个字典都有相同的字段-从1-n个要分组的“维度”字段到1-n个要聚合的度量字段
  • 维度-要按其分组的维度字段列表
  • metrics—要聚合的度量字段列表
  • 我以前解决此问题的方法是使用setdefault:

    struc = {}
    for row in rows:
        year = row['year']
        month = row['month']
        affiliate = row['affiliate']
        website = row['website']
        pgroup = row['product_group']
        sales = row['sales']
        cost = row['cost']
        struc.setdefault(year, {})
        struc[year].setdefault(month, {})
        struc[year][month].setdefault(affiliate, {})
        struc[year][month][affiliate].setdefault(website, {})
        struc[year][month][affiliate][website].setdefault(pgroup, {'sales':0, 'cost':0})
        struc[year][month][affiliate][website][pgroup]['sales'] += sales
        struc[year][month][affiliate][website][pgroup]['cost'] += cost
    
    问题是,如果我查看的是不同的数据集,那么字段名、维度字段的数量和度量字段的数量都会不同


    我看过关于递归函数和defaultdict的帖子,但是(除非我误解了它们),它们要么要求您知道要使用多少维度和度量字段,要么不输出我需要的dictionary对象。

    这比我想象的要简单得多:)

    我的主要问题是如果你有n个维度——当你在每一行的维度之间循环时,如何引用字典的正确级别

    我通过创建指针变量并在每次创建新级别时将其指向字典的新级别来解决这个问题

    def jsonify(data, dimensions, metrics, struc = {}):
        for row in data:
            pointer = struc
            for dimension in dimensions:
                pointer.setdefault(row[dimension], {})
                pointer = pointer[row[dimension]]
            for metric in metrics:
                pointer.setdefault(metric, 0)
                pointer[metric] += row[metric]
        return struc
    

    只是出于兴趣@thefourtheye,你为什么编辑这个?我特别想让函数在Python中使用,所以把它放在问题的标题中是不明智的吗?实际的语言或技术更倾向于放在标记中而不是标题中。这就是我编辑这篇文章的原因。