Skip to main content

Key-value collections

Python Dictionaries: Keys, Lookups, Updates, and Patterns

Dictionaries map unique hashable keys to values and preserve insertion order, making them useful for records, indexes, counts, and configuration.

Pythonbeginner4 min readPython fundamentals

Learning overview

Estimated time
4 minutes
Difficulty
Beginner
Prerequisites
No prior experience required
Learning outcome
Explain python using a clear mental model · Apply python in practical Python work
Last updated
July 18, 2026

Choose strict or optional lookup

Square brackets express that a key is required and raise KeyError when absent. get expresses optional lookup and can supply a default. Membership with in distinguishes a missing key from a stored falsy value.

lookup.py
course = {"title": "Python", "lessons": 28, "published": False}

title = course["title"]
level = course.get("level", "beginner")
if "published" in course:
    print(course["published"])

Iterate and transform mappings

Iteration yields keys. Use items for key-value pairs and values for values. Dictionary comprehensions build indexes and transformed mappings clearly.

dict-comprehension.py
courses = [
    {"slug": "python", "title": "Python"},
    {"slug": "sql", "title": "SQL"},
]
by_slug = {course["slug"]: course for course in courses}

for slug, course in by_slug.items():
    print(slug, course["title"])

Use dedicated tools for counting and grouping

collections.Counter handles counts, while defaultdict can group values without repeated key checks. Use setdefault sparingly when a dedicated collection communicates intent better.

Frequently asked questions

What can be a Python dictionary key?

A key must be hashable with a stable hash and equality behavior, such as strings, numbers, and tuples containing only hashable values.

Do Python dictionaries preserve order?

Yes. Modern Python language semantics preserve insertion order. Updating an existing key does not move its original position.

Topic graph

A taxonomy-generated path through this subject.

  1. Python
  2. Python fundamentals
  3. python
  4. dictionaries
  5. mappings
  6. data-modeling
  7. What Is Python in Programming?
  8. Learn Python: From Fundamentals to Real Applications
  9. Python Tutorial: Build a Command-Line Expense Tracker

Recommended automatically from shared technologies, topics, intent, and difficulty.

Hand-picked companion pages that deepen this topic.

Your next steps

Continue learning

  1. 1glossaryWhat Is Python in Programming?
  2. 2guidesLearn Python: From Fundamentals to Real Applications
  3. 3guidesPython Tutorial: Build a Command-Line Expense Tracker
  4. 4cheatsheetsPython Cheatsheet: Syntax, Collections, Files, and OOP