Skip to main content
Programming from zero

Dictionaries and maps theory + first problem: read values from a config dictionary

easyDictionaries Must-do

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.

flowchart LR A["key: 'host'"] --> B["config dictionary"] --> C["value: 'api.internal'"] classDef key fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef dict fill:#FEF3C7,stroke:#D97706,color:#92400E classDef value fill:#D1FAE5,stroke:#059669,color:#065F46 class A key class B dict class C 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.

TEXT
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:

TEXT
Connecting to api.internal:8443

Approach

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}")