Python Dictionaries: Structure & Hash Maps

Master Python Dictionaries. Learn to store, fetch, and handle key-value pair data. Understand performance and best practices for mappings.

Try Python Dictionaries Code

Overview

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and does not allow duplicates.

Dictionaries are optimized for retrieving values when you know the key, making them incredibly fast for lookups (like a hash map).

From Python 3.7 onwards, dictionaries are officially guaranteed to maintain insertion order.

Code Example

Creating a user configuration profile heavily utilizing nested key-value pairs.

user = {
    "username": "coder123",
    "role": "admin",
    "active": True
}

user["last_login"] = "2026-04-10" # Adding a key
print(f"Username is {user['username']}")

# Iterating over key-value pairs
for key, value in user.items():
    print(f"{key}: {value}")
Terminal Output
Username is coder123
username: coder123
role: admin
active: True
last_login: 2026-04-10

Real-world Use Cases

  • Handling JSON responses from REST APIs
  • Mapping unique IDs to large data objects
  • Storing application configuration parameters

Frequently Asked Questions

What happens if I try to access a key that does not exist?

Using bracket notation (user["name"]) throws a KeyError. Use user.get("name") to return None instead without throwing.

Keep Learning