2015-12-16 13 views
1

我到處都找過了一個解決這個問題的,我無法找到任何這,我想實現的方式工作。功能聚集一組數據,並輸出嵌套的字典

我要創造出有三個參數

  1. data_object Python的功能 - 這是字典的一個列表,其中每個字典有相同的領域 - 從任何地方到組「尺寸」字段的1-N量通過以及從1-n數量的指標字段中的任何位置進行彙總。
  2. 尺寸 - 維字段組由
  3. 指標列表 - 度量字段列表聚集

我以前解決這個問題的方法是使用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但職位(除非我誤解了他們)都要麼需要你知道你要多少的維度和指標領域一起工作或者不輸出字典對象,它是什麼,我需要。

+0

只是出於興趣@thefourtheye的,你爲什麼要修改這個?我特意試圖在Python中使用函數,因此將它放在問題的標題中是不明智的? –

+1

實際的語言或技術在標籤中比在標題中更受歡迎。這就是我編輯它的原因。 – thefourtheye

回答

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