Question

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.

Was it helpful?

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())

OTHER TIPS

You could use a lambda with dict.fromkeys:

In [15]: x = collections.defaultdict(
             lambda: dict.fromkeys(
                 ['flag_name', 'flag_name2', 'flag_name3'], False))

In [16]: x['foo']
Out[16]: {'flag_name': False, 'flag_name2': False, 'flag_name3': False}

Or, to accommodate arbitrary dicts, just return the dict from the lambda:

In [17]: x = collections.defaultdict(lambda: {'flag_name': False, 'flag_name2': False, 'flag_name3': False})

In [18]: x['foo']
Out[18]: {'flag_name': False, 'flag_name2': False, 'flag_name3': False}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top