Dictionaries and maps theory + first problem: read values from a config dictionary
Problem statement
A dictionary stores values under names, called keys. A list finds an item by position (servers[0]). A dictionary finds it by key (config["host"]). Each key is paired with one value, together called a key-value pair, like "host" and "api.internal".
Java calls it a Map (usually a HashMap), and C++ uses std::map. Config files look exactly like this: a name on the left, a setting on the right. All the values here are text ("8443" in quotes), because Java and C++ maps hold one type of value.
To look up a value, give the dictionary its key:
- Python:
config["host"] - Java:
config.get("host") - C++:
config.at("host")
Common mistake: getting the key's spelling or capital letters wrong.
Wrong: config["Host"] (the key is "host", all lowercase)Keys must match exactly. Python stops with a KeyError. Java's get quietly returns null. In C++, config["Host"] would silently add an empty entry, which is why this page uses .at(), which stops with an error instead. The next problem shows how to handle a missing key on purpose.
Your task: given config = {"host": "api.internal", "port": "8443", "env": "prod"}, read the host and the port, then print them in the form Connecting to <host>:<port>.
Expected output:
Connecting to api.internal:8443Approach
Look up each value by its key, store it in a variable, then build the message.
DSA connection: a dictionary is a hash map, one of the most-used tools in DSA problems.
config = {"host": "api.internal", "port": "8443", "env": "prod"}
host = config["host"]
port = config["port"]
print(f"Connecting to {host}:{port}")