【问题标题】:How to create nested python dictionary that has varying levels of nesting and all leaf keys has the same value如何创建具有不同嵌套级别且所有叶键具有相同值的嵌套python字典
【发布时间】:2023-03-02 23:45:01
【问题描述】:

我正在重构意大利面条代码,它有这样一段:

template_dict = {
    "value": "",
    "isIncreased": False,
    "isDecreased": False
}
my_dict = {
    "current_half_result": {
        "home": template_dict,
        "draw": template_dict,
        "away": template_dict
    },
    "full_time_result": {
        "home": template_dict,
        "draw": template_dict,
        "away": template_dict
    },
    "current_half_over_under": {
        "$1_5": {
            "over": template_dict,
            "under": template_dict
        },
        "handicap": ""
    },
    "full_time_over_under": {
        "$2_5": {
            "over": template_dict,
            "under": template_dict
        },
        "handicap": ""
    },
    "next_goal": {
        "home": template_dict,
        "no_goal": template_dict,
        "away": template_dict
    }
}

如您所见,my_dict 变量在所有叶键中具有相同的值 - template_dict。如何以不比当前示例慢的方式从代码中删除重复,同时提高代码的可读性和清洁度。速度是一个重要因素,因为这段代码在我的服务器中每秒执行 3-600 次。而且我不会过多地增加行数或创建额外的功能等。

附:我没有写那个代码,所以不要评判我。由于代码中的强耦合,我不能一次做出大的改变。完整代码请查看this link

【问题讨论】:

  • 这个字典是静态的,只需要定义一次。在模块级别定义,定义不会被执行两次。你确定它正在运行数百次吗?您至少可以将其移至模块级别。
  • @smido,是的,我确定。它只是代码的一部分。它在执行下一行时发生变化。 “value”、“isIncreased”、“isDecreased”键的所有值都在变化。课程的完整代码在这个链接中:pastebin.com/CLQ7SF9g
  • 目前还不是很清楚你在做什么,但也许可以从collections 中检查defaultdict,这可以让你根本不定义结构,只需设置值。你可能需要无限嵌套的字典,命名为InfiniteDicthere
  • @smido 我也这么认为,我自己的实现使用 defaultdict。只是想检查是否有更好的东西。感谢您的精力和时间。

标签: python refactoring dry


【解决方案1】:

这是我自己的解决方案。

def_dict = defaultdict(lambda: {"value": "", "isIncreased": False, "isDecreased": False})
my_dict = defaultdict(lambda: def_dict)
# PyCharm raises warning for two lines below, but it works
my_dict['current_half_over_under'] = defaultdict(lambda: def_dict) 
my_dict['full_time_over_under'] = defaultdict(lambda: def_dict)

要在"full_time_over_under""current_half_over_under" 字典中设置"handicap" 键,我们应该通过my_dict.setdefault('handicap', some_value) 访问它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2020-07-17
    • 1970-01-01
    • 2016-06-21
    • 2021-09-05
    • 2016-07-09
    • 2014-12-27
    相关资源
    最近更新 更多