1👍
✅
If you don’t like to always repeat the same keys put them into a list:
keys = ['audio', 'video', 'sensor', 'backup']
SETTINGS = {
'mode_1': dict.fromkeys(keys, True),
'mode_2': dict.fromkeys(keys, False),
}
If the default settings may different values then you can still avoid repeating the keys using zip
to build the dicts:
SETTINGS = {
'mode_3': dict(zip(keys, [True, False, False, True])),
}
In fact you could specify the values for each mode and then build the dictionary in a dict comprehension:
import itertools as it
keys = ['audio', 'video', 'sensor', 'backup']
SETTINGS_LIST = (
('mode_1', it.repeat(True)),
('mode_2', it.repeat(False)),
('mode_3', [True, False, False, True]),
)
SETTINGS = {mode: dict(zip(keys, values)) for mode, values in SETTINGS_LIST}
This doesn’t do any repetition of value or key literal and dict
and zip
are called only in one place.
Source:stackexchange.com