Search code examples
pythondictionarydefaultdict

How to default a nested defaultdict() to a list of specified length?


I'd like to know how to default a nested defaultdict to a list [0,0,0]. For example, I'd like to make this hierarchical defaultdict.

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]}
        }

To make this nested dictioanry, I did dic01 = defaultdict(dict) and added a dictionary as dic01['year2018']['jan_temperature'] = [8, 9, 10]. My question is if it's possible to update each element of a list without previously binding [0, 0, 0]. In other works, if I make a defaultdict as defaultdict(dict), I have to bind a list [0,0,0] before using it, and I'd like to skip this binding process.

# 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

Solution

  • You can specify that you want a default value of a defaultdict that has a default value of [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)
    

    prints

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

    Which you can treat as a regular nested dictionary