45. Merge settings
Programs often read their settings from several places: built-in defaults first, then a settings file, then what the user typed. Each place can change what the ones before it said.
Write a function merge_settings(*layers) that takes any number of dictionaries and returns one new dictionary with
every key from all of them:
- When a key is in more than one layer, the value from the last of those layers wins.
- A value is replaced as a whole, even when it is itself a dictionary: the layers are not merged inside it.
- With no layers at all, return an empty dictionary
{}.
The order of the keys in the result doesn't matter. The examples show the call itself, since the function takes any number of arguments.
Example 1
merge_settings({"theme": "light", "size": 12},
{"size": 14}){"theme": "light", "size": 14}Example 2
merge_settings({"a": 1}, {"b": 2}, {"a": 3}){"a": 3, "b": 2}Example 3
merge_settings(){}Constraints
- There are 0 to 10 layers, each a dictionary with 0 to 10 keys.
- The keys are strings; the values can be anything.
Submit also runs 6 more tests you can't see.
Practises Function Arguments (lesson 17).
*layersin thedefline collects every argument into one tuple, sofor layer in layers:goes through them in order, however many there are.- Start from an empty dictionary and copy each layer's keys into it: setting a key again replaces its value, so later layers win.
merged.update(layer)copies all of a layer's keys at once. Use a new dictionary rather than changing the first layer, and return it even when there were no layers.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def merge_settings(*layers):
"""Merge settings, later layers winning.
*layers: any number of dicts, from first to last
Returns: dict, every key, each with its value from the
last layer that has it
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.