Python:Python Dictionaries (HashMaps): Key-Value Pairs and Methods
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:

ParameterTypeDescription
keyHashable ObjectImmutable key used to retrieve the mapped value.
valueAny Python ObjectData associated with the key.

Ready-to-Run Code Example

Executable in Compilra

Run 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 hashable

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler