Search code examples
pythondictionarydefaultdict

A Default Dict that default's to a dictionary with pre-generated keys


If there a better way to accomplish this?

from functool import partial
from collections import defaultdict

dict_factory = partial(dict, {'flag_name' : False,
                              'flag_name2' : False,
                              'flag_name3' : True, etc.}

self.ids_with_flags_dictionary = defaultdict(dict_factory)

The goal here being a dictionary of keys(the keys being id's of some kind) that autogenerates the list of default flag states if I call an ID that hasn't been called before.


Solution

  • There's nothing wrong with it exactly, but using partial seems a bit overkill just to return a static value. Why not just:

    defaultFlags = {'flag_name' : False,
    'flag_name2' : False,
    'flag_name3' : False,
    # etc.
    }
    
    self.ids_with_flags_dictionary = defaultdict(lambda: defaultFlags.copy())