Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Dictionaries: Keys, Values, and Practical Patterns

Data structures · Tutorial 17

Python Dictionaries: Keys, Values, and Practical Patterns

Store and retrieve key-value data with dictionaries, iterate over items, and use get, update, and comprehensions.

Open the compilerPractice exercises
beginner9 min readUpdated November 19, 20264 learning goals
On this page
  1. Accessing values
  2. Adding and updating
  3. Removing entries
  4. Checking keys
  5. Iterating
  6. Counting with a dictionary
  7. Dictionary comprehensions
  8. Nested data
  9. Practice

What you will learn

  • Create dictionaries and access values
  • Use get() to handle missing keys safely
  • Iterate over keys, values, and items
  • Build dictionaries with comprehensions
Before this lesson: Python Lists: Creation, Indexing, and Iteration, Python Tuples: Immutable Sequences and Unpacking

A dictionary maps keys to values. Keys must be hashable and unique; values can be anything.

Python
student = {
    "name": "Ada",
    "score": 95,
    "passed": True,
}

Curly braces surround the dictionary. Each entry is key: value, and entries are separated by commas.

Accessing values#

Python
student = {"name": "Ada", "score": 95}

print(student["name"])   # Ada
print(student["score"])  # 95

Accessing a missing key raises KeyError. Use get() when absence is expected:

Python
print(student.get("email"))            # None
print(student.get("email", "unknown")) # unknown

The second argument is the default returned when the key is missing. The default expression is evaluated before get() is called, so avoid expensive work there unless it is necessary.

Adding and updating#

Python
student = {"name": "Ada"}

student["score"] = 95
student["score"] = 97
student.update({"passed": True, "level": 2})

print(student)
Expected output

{'name': 'Ada', 'score': 97, 'passed': True, 'level': 2}

Assigning to an existing key replaces its value. update() merges another dictionary or an iterable of pairs.

Removing entries#

Python
student = {"name": "Ada", "score": 95}

score = student.pop("score")   # remove and return
del student["name"]            # remove by key
student.clear()                # remove everything

pop() accepts a default for missing keys: student.pop("email", None). del raises KeyError when the key is absent.

Checking keys#

Python
student = {"name": "Ada"}

print("name" in student)    # True
print("email" in student)   # False
print(len(student))         # 1

Membership tests keys, not values. To test a value, use "Ada" in student.values().

Iterating#

Python
scores = {"Ada": 90, "Grace": 95, "Linus": 88}

for name in scores:
    print(name)

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

for name, score in scores.items():
    print(f"{name}: {score}")

Iteration order is insertion order. Sorting keys explicitly makes output deterministic:

Python
for name in sorted(scores):
    print(name, scores[name])

Counting with a dictionary#

A very common pattern accumulates counts:

Python
words = ["apple", "banana", "apple", "cherry", "apple"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)
Expected output

{'apple': 3, 'banana': 1, 'cherry': 1}

get() supplies 0 for a new word, so the addition always works.

Dictionary comprehensions#

Python
numbers = [1, 2, 3, 4]

squares = {number: number ** 2 for number in numbers}
print(squares)

lengths = {word: len(word) for word in ["one", "three", "seven"]}
print(lengths)

A comprehension is readable when the key and value are simple expressions.

Nested data#

Python
users = {
    "ada": {"score": 95, "active": True},
    "grace": {"score": 88, "active": False},
}

for username, profile in users.items():
    status = "active" if profile["active"] else "inactive"
    print(f"{username}: {profile['score']} ({status})")

Nested dictionaries are common in JSON data. Access one level at a time and check for missing keys when the structure is not guaranteed.

Keys must be immutable

Use strings, numbers, or tuples as keys. Lists and dictionaries are unhashable and cannot be keys. If you need a composite key, a tuple is usually the answer.

Practice#

Read a sentence, split it into words, and count each word with a dictionary. Print the words in alphabetical order with their counts. Then print only the words that appear more than once.

Previous tutorialPython Tuples: Immutable Sequences and UnpackingNext tutorialPython Sets: Unique Values and Set Operations

Related tutorials

beginner

Python Sets: Unique Values and Set Operations

Remove duplicates with sets, test membership quickly, and use union, intersection, difference, and symmetric difference.

8 min read
beginner

Python Functions: Define, Call, and Return Values

Write reusable code with def, pass arguments, return results, and use docstrings to document behaviour.

9 min read

On this page

  1. Accessing values
  2. Adding and updating
  3. Removing entries
  4. Checking keys
  5. Iterating
  6. Counting with a dictionary
  7. Dictionary comprehensions
  8. Nested data
  9. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.