Tutorials Logic, IN info@tutorialslogic.com

Python Dictionaries: Keys, Lookup, Safe Access, and Merging

Python Dictionaries

Use a dictionary when direct lookup by a stable key is more important than positional order.

Prefer get() or an explicit membership check when missing keys are expected. Use direct indexing when a missing key should fail loudly because it means the data contract is broken.

The practical skill is deciding whether absent data is normal, optional, or a bug.

Python Dictionary

A dictionary stores data as key-value pairs. Keys must be unique and immutable (strings, numbers, tuples). Values can be anything. Dictionaries are ordered as of Python 3.7+.

  • Key-value pairs - access values by key, not index
  • Ordered (Python 3.7+) - insertion order preserved
  • Mutable - add, update, delete entries
  • Keys must be unique and hashable
  • O(1) average lookup by key

Creating Dictionaries

Create Records and Lookup Tables

Create Records and Lookup Tables
empty = {}
person = {"name": "Alice", "age": 25, "city": "London"}

# dict() constructor
config = dict(host="localhost", port=5432, debug=True)

# From list of tuples
pairs = dict([("a", 1), ("b", 2), ("c", 3)])

# Nested dictionary
student = {
    "name": "Bob",
    "grades": {"math": 90, "english": 85},
    "hobbies": ["coding", "reading"]
}

print(type(person))   # <class 'dict'>
print(len(person))    # 3

Access and Update

Access & Modify

Access & Modify
person = {"name": "Alice", "age": 25, "city": "London"}

# Access by key
print(person["name"])         # Alice
print(person.get("age"))      # 25
print(person.get("email"))    # None (no KeyError)
print(person.get("email", "N/A"))  # N/A (default value)

# Modify
person["age"] = 26            # update existing
person["email"] = "alice@example.com"  # add new key

# Delete
del person["city"]
removed = person.pop("email")  # removes and returns value
print(removed)  # alice@example.com

# Nested access
student = {"grades": {"math": 90, "english": 85}}
print(student["grades"]["math"])  # 90

Iterating Dictionaries

Looping Through Dicts

Looping Through Dicts
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}

# Iterate keys (default)
for name in scores:
    print(name)

# Iterate values
for score in scores.values():
    print(score)

# Iterate key-value pairs
for name, score in scores.items():
    print(f"{name}: {score}")

# Check key existence
if "Alice" in scores:
    print("Alice found!")

# Dict comprehension
squared = {x: x**2 for x in range(1, 6)}
print(squared)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Filter with comprehension
high_scores = {k: v for k, v in scores.items() if v >= 90}
print(high_scores)  # {'Alice': 95, 'Charlie': 92}

Dictionary Methods

Method Description
get(key, default) Return value or default (no KeyError)
keys() Return all keys
values() Return all values
items() Return all key-value pairs as tuples
update(d) Merge another dict into this one
pop(key) Remove and return value by key
popitem() Remove and return last inserted pair
setdefault(key, val) Return value; set if key missing
clear() Remove all items
copy() Return shallow copy
fromkeys(keys, val) Create dict from keys with same value

Useful Methods

Useful Methods
d = {"a": 1, "b": 2}

# update - merge dicts
d.update({"c": 3, "d": 4})
print(d)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Merge with | operator (Python 3.9+)
d1 = {"x": 1}
d2 = {"y": 2}
merged = d1 | d2
print(merged)  # {'x': 1, 'y': 2}

# setdefault - add key only if it doesn't exist
counts = {}
for char in "hello":
    counts.setdefault(char, 0)
    counts[char] += 1
print(counts)  # {'h': 1, 'e': 1, 'l': 2, 'o': 1}

# fromkeys
keys = ["name", "age", "email"]
template = dict.fromkeys(keys, None)
print(template)  # {'name': None, 'age': None, 'email': None}

# Sorting a dict by value
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
print(sorted_scores)  # {'Alice': 95, 'Charlie': 92, 'Bob': 87}

Dictionaries in Real Programs

  • Use a dictionary when each value needs a meaningful key.
  • Use get() when a missing key is normal and direct indexing when a missing key should fail.
  • Check keys before merging dictionaries so newer values do not overwrite important old values silently.
  • Use dictionaries for records, counters, settings, API responses, and lookup tables.
Dictionary lookup check

Can You Read Dictionary Data Safely?

5 checks
  • A dictionary stores data as key-value pairs.
  • Keys must be unique and immutable (strings, numbers, tuples).
  • Dictionaries are ordered as of Python 3.7+.
  • Dictionaries map keys to values, which makes them the right tool for lookup-heavy data, structured records, configuration, and nested payloads.
  • Focus on hashable keys, safe access, nested updates, and the difference between a shallow copy and an independent nested structure.

Dictionary Decisions

0 of 2 checked

Q1. What does user.get("theme", "light") do when theme is missing?

Q2. When is direct indexing such as user["email"] useful?

Dictionary Lookup Traps

  • Assuming a key exists

    Use in or get() when data may come from users, files, or APIs.
  • Using many separate lists for related data

    Use dictionaries so each record keeps named fields together.
  • Overwriting a value accidentally

    Check whether the key already exists before assigning when duplicates matter.

Try this next

Build a Lookup Table

0 of 3 completed

  1. Create a user dictionary with name, email, and active fields.
  2. Use a dictionary to count how many times each word appears in a list.
  3. Print a theme setting with a fallback when the key is missing.

Questions About Dictionary Lookup

Use dict.get(key, default_value). If the key does not exist, it returns the default instead of raising KeyError. Example: age = person.get("age", 0)

Python 3.9+: merged = dict1 | dict2. Python 3.5+: merged = {**dict1, **dict2}. To update in place: dict1.update(dict2). The last value wins for duplicate keys.

defaultdict(factory) from collections module automatically creates a default value for missing keys. Example: from collections import defaultdict; d = defaultdict(list); d["key"].append(1) - no KeyError.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.