Home > Blockchain >  Multi-Level Configs Using config.setdefault()
Multi-Level Configs Using config.setdefault()

Time:01-16

I'm looking for an easy way to handle multi-level dictionaries using the config.setdefault() method. Here's an example:

config = {}

config.setdefault("key1", 10)
config.setdefault("key2", {'x': 1, 'y': 2})
config.setdefault("key3", 5)

For "key2", I would like to set defaults for both 'x' and 'y' keys. Is this possible? Let me know if I need to clarify my question.

CodePudding user response:

.setdefault() doesn't work that way. It accepts a single value argument.

One could .update(new_dict) to incorporate new key / value pairs. But if it lists any pre-existing keys, the existing values would be overwritten. So that's not quite it.

You are looking for "merge dictionaries". We construct a new dict, and give the old config a chance to overwrite any newly proposed values. Notice that c retains its old value.

>>> config = dict(c=1)
>>> config = {**{'x': 2, 'y': 3, 'c': 4}, **config}
>>> config
{'x': 2, 'y': 3, 'c': 1}

If you have dictionaries a and b, then

{**a, **b}

will merge them.

CodePudding user response:

I'm going to answer my own question here, it was a simpler solution than I thought. The following code does what I was wanting.

config = {}

config.setdefault("key1", 10)
config.setdefault("key2", {}).setdefault('x', 1)
config.setdefault("key2", {}).setdefault('y', 2)
config.setdefault("key3", 5)

print(config)

{'key1': 10, 'key2': {'x': 1, 'y': 2}, 'key3': 5}

  • Related