ChainMap in Python

Level 4258 keystrokes

This uses ChainMap to combine multiple dictionaries into a single view, with earlier dicts taking priority.

Python code

# Import ChainMap from collections
1from collections import ChainMap
2
# Default values
3defaults = {"color": "red", "size": "medium"}
# User preferences that override only color
4user_prefs = {"color": "blue"}
5
# Earlier dicts take priority: user_prefs is searched first
6config = ChainMap(user_prefs, defaults)
7
# Found in user_prefs: blue
8print(f"color: {config['color']}")
# Not in user_prefs, so it comes from defaults: medium
9print(f"size: {config['size']}")
# keys() merges the keys of all dicts without duplicates
10print(f"keys: {list(config.keys())}")

Output

color: blue
size: medium
keys: ['color', 'size']
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 18
  • :× 6
  • (× 6
  • )× 6
  • {× 5
  • }× 5
  • '× 4
  • =× 3
  • _× 2
  • ,× 2

More Python examples at level 4

← Python typing practice