我需要在 Python 中创建一个类似于此的多层字典
"objects": {
"LOCATION 1": {
"EMPLOYEE 1": {
"19": 3,
"20": 0,
"21": 0,
"40": 4
},
"EMPLOYEE 2": {
"24": 0,
"42": 11,
"43": 13
}
},...
...
...
这是一个字典,显示每个员工每周按位置记录的工作时间。
典型的记录遵循这种格式 [LOCATION,EMPLOYEE,HOURS_LOGGED,DATE],对于每条记录,我从日期中得出周数。
我目前使用 10,000 条记录大约需要 10 秒的算法如下
result={}
if (location in result):
if (engineer in result[location]):
if (week in result[location][engineer]):
result[location][engineer][week]=result[location][engineer][week]+laborminutes
else:
result[location][engineer][week]=laborminutes
else:
result[location][engineer]={week:laborminutes}
else:
result[location]={engineer:{week:laborminutes}}
无论如何我可以改进
最佳答案
collections.defaultdict
提供一种方式:
from collections import defaultdict
result = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
result[location][engineer][week] += laborminutes
collections.defaultdict
是 dict
的子类。我们定义了一个dict(dict(dict(int)))
的嵌套结构。由于 int
的默认值为 0,我们可以轻松地通过 laborminutes
给定任意键 location
、engineer
来增加值, 周
。
关于Python - 提高我的算法速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643921/