gpt4 book ai didi

python - 使用映射器字典转换嵌套字典值

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:36 26 4
gpt4 key购买 nike

我正在寻找一个优雅的 pythonic 解决方案

我有两个字典,一个输入字典和一个包含映射信息的字典 - 见下文。我的目标是将输入字典中的任何值转换为相应的 mapper 值,如果它们具有相同的“关键路径”意味着 input_dico[k1][k2] 已更改到值 mapper_dico[k1][k2] 而不是 mapper_dico[k3][k2]

mapper = {
'data_labels': {
'position': {
'outside_end': 'XL_LABEL_POSITION.OUTSIDE_END',
'inside_end': 'XL_LABEL_POSITION.INSIDE_END'
}
},
'category_axis': {
'major_tick_mark': {
'None': 'XL_TICK_MARK.NONE',
},
'tick_label_position': {
'None': 'XL_TICK_LABEL_POSITION.NONE',
'high': 'XL_TICK_LABEL_POSITION.HIGH',
'low': 'XL_TICK_LABEL_POSITION.LOW',
},
},
'chart': {
'clustered_column': 'XL_CHART_TYPE.COLUMN_CLUSTERED',
'clustered_bar': 'XL_CHART_TYPE.BAR_CLUSTERED',
'stacked_bar': 'XL_CHART_TYPE.BAR_STACKED',
},
}

示例输入 dico:

{'category_axis': {'format': {'line': {'fill': 'A5300F'}},
'has_major_gridlines': False,
'major_tick_mark': 'None',
'tick_label_position': 'None',
'visible': True},
'chart': 'clustered_column',
'data_labels': {'font': {'size': 9},
'number_format': '#0.0%',
'position': 'outside_end'},
'value_axis': {'has_major_gridlines': False, 'visible': False}}

所以你在这里看到,示例 input_dico['data_labels']['position']:'outside_end', input_dico['category_axis']['tick_label_position']:' None'input_dico['chart']:'clustered_column'都得转换!

我目前是这样做的,这真的很笨拙且难以理解,所以我正在寻找最有可能递归、简短的东西。 如果有人有更好的解决方案,我也愿意放弃整个 use-a-dictionary-to-map-values 方法!

def _reformat(display): #display is the input_dico
"""Change certain values to pptx-python classes."""
for k1, v1 in mapper.items():
if k1 in display:
if isinstance(v1, str):
display[k1] = mapper[k1]
else:
for k2, v2 in v1.items():
if k2 in display[k1]:
for k3 in v2:
if k3 == display[k1][k2]:
display[k1][k2] = mapper[k1][k2][k3]
return display

最佳答案

代码:

from typing import Union, Hashable, Any

def _reformat(parent: Union[dict, Hashable], mapping: dict) -> Union[dict, Any]:
"""Recursive function that transforms only these dictionary values which keys correspond to a `mapping` dict."""
if isinstance(parent, dict):
node = {}
for key, value in parent.items():
try:
node[key] = _reformat(value, mapping[key])
except KeyError:
node[key] = value
return node
else:
return mapping[parent]

示例:

mapper = {'data_labels': {'position': {'outside_end': 'XL_LABEL_POSITION.OUTSIDE_END',
'inside_end': 'XL_LABEL_POSITION.INSIDE_END'}},
'category_axis': {'major_tick_mark': {'None': 'XL_TICK_MARK.NONE'},
'tick_label_position': {'None': 'XL_TICK_LABEL_POSITION.NONE',
'high': 'XL_TICK_LABEL_POSITION.HIGH',
'low': 'XL_TICK_LABEL_POSITION.LOW'}},
'chart': {'clustered_column': 'XL_CHART_TYPE.COLUMN_CLUSTERED',
'clustered_bar': 'XL_CHART_TYPE.BAR_CLUSTERED',
'stacked_bar': 'XL_CHART_TYPE.BAR_STACKED'}}

input_dict = {'category_axis': {'format': {'line': {'fill': 'A5300F'}},
'has_major_gridlines': False,
'major_tick_mark': 'None',
'tick_label_position': 'None',
'visible': True},
'chart': 'clustered_column',
'data_labels': {'font': {'size': 9},
'number_format': '#0.0%',
'position': 'outside_end'},
'value_axis': {'has_major_gridlines': False, 'visible': False}}

converted_dict = _reformat(input_dict, mapper)
import pprint
pprint.pprint(converted_dict)

输出:

{'category_axis': {'format': {'line': {'fill': 'A5300F'}},
'has_major_gridlines': False,
'major_tick_mark': 'XL_TICK_MARK.NONE',
'tick_label_position': 'XL_TICK_LABEL_POSITION.NONE',
'visible': True},
'chart': 'XL_CHART_TYPE.COLUMN_CLUSTERED',
'data_labels': {'font': {'size': 9},
'number_format': '#0.0%',
'position': 'XL_LABEL_POSITION.OUTSIDE_END'},
'value_axis': {'has_major_gridlines': False, 'visible': False}}

关于python - 使用映射器字典转换嵌套字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com