#80 · Recursion and backtracking · Intermediate · 70 XP · about 12 min
Settings files often nest groups inside groups. Write flatten_dict(d) that turns a dictionary whose values may themselves be dictionaries, to any depth, into a flat dictionary. Each value that is not a dictionary is stored under the path of keys that leads to it, joined with dots.
Keys appear in the order you meet them reading the original from top to bottom, going into each inner dictionary as soon as you reach it. All keys are strings, and the original dictionary must not be changed.
flatten_dict({"a": 1, "b": {"c": 2, "d": {"e": 3}}}) # returns {'a': 1, 'b.c': 2, 'b.d.e': 3} flatten_dict({"db": {"host": "localhost", "port": 5432}, "debug": True}) # returns {'db.host': 'localhost', 'db.port': 5432, 'debug': True} flatten_dict({}) # returns {}
An empty inner dictionary holds no values, so it leaves nothing behind. Other values, such as lists, are kept as they are, even when they contain dictionaries.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.