python - 如何将嵌套的 defaultdict() 默认为指定长度的列表?

标签 python dictionary defaultdict

我想知道如何将嵌套的defaultdict默认为列表[0,0,0]。例如,我想将这个分层默认字典设置为默认字典。

dic01 = {'year2017': {'jul_to_sep_temperature':[25, 20, 17], 
                      'oct_to_dec_temperature':[10,  8,  7]},
         'year2018': {'jan_to_mar_temperature':[ 8,  9, 10].
                      'apr_to_jun_temperature':[ 0,  0,  0]}
        }

为了制作这个嵌套字典,我做了 dic01 = defaultdict(dict) 并添加了一个字典 dic01['year2018']['jan_Temperature'] = [8, 9, 10 ]。我的问题是是否可以在不事先绑定(bind) [0, 0, 0] 的情况下更新列表的每个元素。在其他作品中,如果我将 defaultdict 设置为 defaultdict(dict),则必须在使用它之前绑定(bind)一个列表 [0,0,0],并且我想跳过此绑定(bind)过程。

# The way I do this
dic01['year2018']['jul_to_sep_temperature'] = [0,0,0]    # -> how to omit this procedure?
dic01['year2018']['jul_to_sep_temperature'][0] = 25

# The way I want to do this
dic01['year2018']['jul_to_sep_temperature'][0] = 25      # by the end of July

最佳答案

您可以指定需要 defaultdict 的默认值,其默认值为 [0, 0, 0]

from collections import defaultdict

dic01 = defaultdict(lambda: defaultdict(lambda: [0, 0, 0]))

dic01['year2018']['jul_to_sep_temperature'][0] = 25

print(dic01)

打印

defaultdict(<function <lambda> at 0x7f4dc28ac598>, {'year2018': defaultdict(<function <lambda>.<locals>.<lambda> at 0x7f4dc28ac510>, {'jul_to_sep_temperature': [25, 0, 0]})})

您可以将其视为常规嵌套字典

关于python - 如何将嵌套的 defaultdict() 默认为指定长度的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49331336/

相关文章:

python - 带默认值的嵌套字典

python - 在python中对相似值进行分组和求和

python - 将 defaultdict 传递给 df

python - 如何在现有窗口应用程序发出信号后显示另一个小部件? (两个 GUI 都是使用 pyuic5 从 ui 转换而来)

python - 如何克隆 Python 生成器对象?

python - 如何将递增的数字附加到字典值中?

python - Pandas :根据字典更改数据框值并删除不匹配的行

python - 如何创建像 ActivePython 这样的 Python 发行版?

python - 解析 XML Python

JavaScript 语法错误 : Unexpected end of input