为了账号安全,请及时绑定邮箱和手机立即绑定

如何创建具有不同嵌套级别且所有叶键具有相同值的嵌套 python 字典

如何创建具有不同嵌套级别且所有叶键具有相同值的嵌套 python 字典

慕田峪7331174 2022-01-05 20:14:27
我正在重构意大利面条式代码,它有这样一段代码: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 次。而且我不会过多地增加行数或创建附加功能等。PS我没有写那个代码,所以不要评判我。由于代码的强耦合性,我不能一下子做出大的改变。
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

这是我自己的解决方案。


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)

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


查看完整回答
反对 回复 2022-01-05
  • 1 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号