我想拆分一个Python字典,将密钥分成多个密钥,同时将每个密钥的值平分。
示例数据:
{'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}
我想转换为:
{'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}
到目前为止我的代码:
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")
输出:
{'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}
有问题的词典是Vector。
答案 0 :(得分:1)
我不确定你想如何命名你的" split"键,但生成器功能应该是一个简单的方法来实现你想要的。请看这个例子,记住键的名称是错误的。
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)
然后,
d = {'S-NSW-BAC-ENG': 15, 'S-NSW-BAC-FBE': 30}
dict(gen(d))
将产生:
{'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}