我正在重构意大利面条代码,它有这样的一块:
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-6百次。而且我不会太多地增加行数或创建额外的功能等。
附:我没有写那段代码,所以不要评判我。由于代码中的强耦合,我无法立刻做出重大改变。有关完整代码,请查看this link
这是我自己的解决方案。
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)
访问它