2015-06-19 108 views
1

施加從值百分比欲細分一個字典,同時施加的值(其是百分比,到另一個的值細分嵌套字典,而在Python

我有那些數據集:

{'C-STD-B&M-SUM': {datetime.date(2015, 5, 20): 0.21484699999999998, 
       datetime.date(2015, 5, 21): 0.245074, 
       datetime.date(2015, 5, 22): 0.27874} 

{'G-CAM-BAC-SUM': {datetime.date(2015, 5, 20): 0.13294399999999998, 
       datetime.date(2015, 5, 21): 0.151648, 
       datetime.date(2015, 5, 22): 0.17248, 
       datetime.date(2015, 5, 23): 0.195664} 

{'G-CAM-BAC-XS': 0.06, 'G-CAM-BAC-XXS': 0.01, 'G-CAM-BAC-XL': 0.11, 'G-CAM-BAC-S': 0.19, 'G-CAM-BAC-L': 0.26, 'G-CAM-BAC-XXL': 0.03, 'G-CAM-BAC-M': 0.35} 

{'C-STD-B&M-XL': 0.3, 'C-STD-B&M-XXL': 0.11, 'C-STD-B&M-S': 0.06, 'C-STD-B&M-M': 0.2, 'C-STD-B&M-XS': 0, 'C-STD-B&M-L': 0.32} 

預期輸出:

{'C-STD-B&M-XL': {datetime.date(2015, 5, 20): 0.21484699999999998*0.3, 
      datetime.date(2015, 5, 21): 0.245074*0.3, 
      datetime.date(2015, 5, 22): 0.27874*0.3} 

{'C-STD-B&M-XXS': {datetime.date(2015, 5, 20): 0.21484699999999998*0.1, 
      datetime.date(2015, 5, 21): 0.245074*0.1, 
      datetime.date(2015, 5, 22): 0.27874*0.1} 

{'C-STD-B&M-XXL': {datetime.date(2015, 5, 20): 0.21484699999999998*0.11, 
      datetime.date(2015, 5, 21): 0.245074*0.11, 
      datetime.date(2015, 5, 22): 0.27874*0.11} 

等等,所有的詞典請注意,我需要的值相乘的結果,而不是語句,剛剛離開。讓他們更清楚。

到目前爲止我的代碼(部分):

def apply_size_distribution(dictionary_with_temporal_distribution): 
    gown_cap_size = get_size_distribution('G2:G7', 'H2:H7') 
    cap_medium_demand = gown_cap_size['C-STD-B&M-M'] 
    for k, v in dictionary_with_temporal_distribution.items(): 
     if k == "C-STD-B&M-SUM": 
      dictionary_with_temporal_distribution['C-STD-B&M-M'] = dictionary_with_temporal_distribution.pop('C-STD-B&M-SUM') 
      for k, v in dictionary_with_temporal_distribution['C-STD-B&M-M'].items(): 
       dictionary_with_temporal_distribution["{}".format(k)] = v * cap_medium_demand 

但是我卻越來越好老字典迭代過程中發生變化。此外,使用我的代碼,我將不得不復制並粘貼每個大小的代碼,只將Key的名稱更改爲適當的大小。我想知道是否有更強大的方法。

回答

0

你所得到的dictionary_with_temporal_distribution在你的代碼,因爲改變你改變它 -

dictionary_with_temporal_distribution["{}".format(k)] = v * cap_medium_demand 

相反,你應該考慮在開始創建一個新的字典,也許和元素添加到它,你繼續處理的最終回報它。

此外,而不是硬編碼值,像你這樣 - gown_cap_size['C-STD-B&M-M'] - k == "C-STD-B&M-SUM",你應該使用string.rsplit('-', 1)[0]找出共同部分 - C-STD-B&M,然後使用該平等。

你的代碼看起來像 -

def apply_size_distribution(dictionary_with_temporal_distribution): 
    gown_cap_size = get_size_distribution('G2:G7', 'H2:H7') 
    retlist = {} 
    for cap_demand in grown_cap_size: 
     for k, v in dictionary_with_temporal_distribution.items(): 
      if k.rsplit('-', 1)[0] == cap_demand.rsplit('-', 1)[0]: 
       if cap_demand not in retlist: 
        retlist[cap_demand] = {} 
       temp = retlist[cap_demand] 
       for k1, v1 in dictionary_with_temporal_distribution[k].items(): 
        temp[k1] = v1 * grown_cap_size[cap_demand] 
    return retlist 
+0

編輯:添加返回retlist部分。 –