25 XP

45. Merge settings

Beginner dictionaries

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

Inputmerge_settings({"theme": "light", "size": 12}, {"size": 14})
Output{"theme": "light", "size": 14}
ExplanationThe second layer's size wins.

Example 2

Inputmerge_settings({"a": 1}, {"b": 2}, {"a": 3})
Output{"a": 3, "b": 2}
ExplanationThe last layer with "a" says 3.

Example 3

Inputmerge_settings()
Output{}
ExplanationNo layers, so no 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).

Code
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