Split Python dictionary into multiple keys, dividing the values equally

I want to split a Python dictionary, dividing keys into multiple ones, whilst dividing the values of each key equally.

Sample data:

{'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}

I want to convert to:

{'H-NSW-BAC-ENG': 5, 'C-STD-B&M-SUM': 5, 'G-CAM-BAC-SUM': 5, 'H-NSW-BAC-FBE': 10, 'C-STD-B&M-SUM': 10, 'G-CAM-BAC-SUM': 10}

My code so far:

from openpyxl import load_workbook

wb = load_workbook("scm.xlsx")

sheets_list = wb.get_sheet_names()

demand_input_sheet = wb['User pathways']
process_description_sheet = wb['Process description']
temporal_demand_sheet = wb['temporal demand distrobution']
demand_input_sheet = wb['demand input vectors']
sku_sheet = wb['Set to SKU array']
size_distribution_sheet = wb['size distribution']

Vector = {}
SKUs = []
Values = []

# For loop used to append the SKUs to a list. It does so by iterating through the selected cells from the spreadsheet
for row in demand_input_sheet.iter_rows('A5:A16'):
        for cell in row:
            SKUs.append(cell.value)

# Same things as above, but used to append the Values
for row in demand_input_sheet.iter_rows('B5:B16'):
        for cell in row:
            Values.append(cell.value)

Vector = dict(zip(SKUs, Values))

print(Vector)
wb.save("manipulated.xlsx")

Output:

{'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}

Dictionary in question is Vector.

Upvotes: 4

Views: 1702

Answers (1)

Andrzej Pronobis
Andrzej Pronobis

Reputation: 36086

I'm not exactly sure how you want to name your "split" keys, but a generator function should be an easy way to achieve what you want. Look at this example, keeping in mind that the names of the keys are wrong.

def gen(d):
    for k, v in d.items():
        yield ('H' + k[1:], v / 3)
        yield ('C' + k[1:], v / 3)
        yield ('G' + k[1:], v / 3)

Then, for

d = {'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}

dict(gen(d))

will produce:

{'C-NSW-BAC-ENG': 5.0,
 'G-NSW-BAC-ENG': 5.0,
 'H-NSW-BAC-ENG': 5.0,
 'C-NSW-BAC-FBE': 10.0,
 'G-NSW-BAC-FBE': 10.0,
 'H-NSW-BAC-FBE': 10.0}

Upvotes: 1

Related Questions