Programming from zero

Iterate over a config dictionary's keys and values

easyDictionaries

Problem statement

You have already looped over a dictionary's keys. Often you want the key and its value together, for example to print every setting in a config. Each language has a way to loop over the whole key-value pair at once.

Common mistake: trying to get both parts from a plain loop.

TEXT
Wrong: for key, value in config:

A plain for loop over a dictionary gives only the keys, one at a time. Python then tries to split each key (a piece of text) into two parts and fails with a ValueError. Ask for the pairs explicitly with .items().

Your task: given config = {"host": "api.internal", "port": "8443", "timeout": "30"}, print every setting on its own line in the form <key> = <value>.

Expected output:

TEXT
host = api.internal
port = 8443
timeout = 30

Approach

Loop over the key-value pairs:

  • Python: for key, value in config.items(): gives both parts on each pass. (config.keys() gives just keys and config.values() gives just values.)
  • Java: for (Map.Entry<String, String> entry : config.entrySet()), then entry.getKey() and entry.getValue().
  • C++: for (const auto& entry : config), then entry.first (the key) and entry.second (the value).

Note on order: the keys here are already in alphabetical order, so Python, Java's LinkedHashMap (insertion order) and C++'s std::map (sorted order) all print the same thing.

DSA connection: looping over every key-value pair is how you read results out of a hash map.

config = {"host": "api.internal", "port": "8443", "timeout": "30"}
for key, value in config.items():
    print(f"{key} = {value}")