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

时间:2015-12-16 12:34:37

标签: python python-2.7 recursion defaultdict

我已经全神贯注地找到了解决这个问题的方法,而且我无法找到任何可以实现的方式。

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

  1. data_object - 这是一个词典列表,其中每个词典具有相同的字段 - 从1-n量的'维度'要分组的字段,以及要汇总的1-n个度量字段的任何位置。
  2. dimensions - 要按
  3. 分组的维度字段列表
  4. metrics - 要聚合的指标字段列表
  5. 我之前解决此问题的方法是使用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的帖子但是(除非我误解了它们)它们要么你要么知道要使用多少维度和度量字段,要么他们不输出字典对象。我需要什么。

1 个答案:

答案 0 :(得分:1)

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

我的主要问题是如果你有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