Python•Dictionaries
Python Dictionaries (HashMaps): Key-Value Pairs and Methods
Backed by highly optimized hash tables, Python dicts deliver O(1) average lookup times. Keys can be strings, numbers, or tuples.
Syntax
my_dict = {"key": "value"}
val = my_dict.get("key", default_value)
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| key | Hashable Object | Immutable key used to retrieve the mapped value. |
| value | Any Python Object | Data associated with the key. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# Python Dictionary Manipulation
user_profile = {
"username": "coder_99",
"email": "[email protected]",
"reputation": 450,
"is_pro": True
}
# Safe lookup with .get()
location = user_profile.get("location", "Not specified")
print(f"User: {user_profile['username']}")
print(f"Location: {location}")
# Adding & updating entries
user_profile["reputation"] += 50
user_profile["role"] = "Administrator"
# Iterating over key-value pairs
print("\nProfile Summary:")
for key, value in user_profile.items():
print(f" {key.capitalize()}: {value}")Expected Output:
User: coder_99 Location: Not specified Profile Summary: Username: coder_99 Email: [email protected] Reputation: 500 Is_pro: True Role: Administrator
How It Works: Step-by-Step
- Lines 10: Uses .get() with a default fallback to avoid KeyError on missing keys.
- Lines 15-16: Updates existing values and adds new key-value pairs.
- Lines 20-21: Iterates through dictionary using .items() unpacking.
Key Concepts
- Accessing a missing key via dict[key] raises KeyError. Use dict.get(key, default) for safety.
- Dictionaries maintain insertion order in Python 3.7+.
- Dictionary keys must be immutable types (strings, numbers, tuples).
Common Mistake: Using unhashable types like lists as dictionary keys
Lists are mutable and cannot be hashed. Use tuples instead as compound keys.
❌ Incorrect
data = {[1, 2]: "coords"} # TypeError: unhashable type: 'list'✅ Correct
data = {(1, 2): "coords"} # Valid: tuple is hashableRelated Python Tutorials & Compiler
Python Lists: Operations, Slicing, and Built-in Methods
Lists are ordered, mutable collections of items. They are one of the most versatile built-in data types in Python.
Python Tuples and Sets: Immutability and Unique Collections
Tuples are immutable ordered sequences, while Sets are unordered collections of unique elements with set mathematics.
Python Strings: Slicing, Escaping, and Built-in Methods
Strings in Python are immutable sequences of Unicode characters with rich built-in transformation methods.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.