Iterate over a config dictionary's keys and values
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.
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:
host = api.internalport = 8443timeout = 30Approach
Loop over the key-value pairs:
- Python:
for key, value in config.items():gives both parts on each pass. (config.keys()gives just keys andconfig.values()gives just values.) - Java:
for (Map.Entry<String, String> entry : config.entrySet()), thenentry.getKey()andentry.getValue(). - C++:
for (const auto& entry : config), thenentry.first(the key) andentry.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}")