Skip to main content

Python Tutorial 4.3 - Dictionaries in Python

Welcome to the “Dictionaries in Python” tutorial!


Overview

Dictionaries store key‑value pairs and are insertion‑ordered (Python 3.7+), mutable mappings.

Creating Dictionaries

student = {"name": "Alice", "age": 25, "major": "CS"}
empty = {}

Common Operations

  • Accessing Values:
    print(student["name"])   # "Alice"
    
  • Adding/Updating Items:
    student["gpa"] = 3.8
    student["age"] = 26
    
  • Removing Items:
    student.pop("major")
    
  • Keys, Values, and Items:
    student.keys()    # dict_keys(["name", "age", "gpa"])
    student.values()  # dict_values(["Alice", 26, 3.8])
    student.items()   # dict_items([("name","Alice"),...])
    

Iterating

for key, value in student.items():
    print(f"{key}: {value}")

Key Takeaways

  • Use dictionaries when you need fast lookups by key.
  • Methods like pop(), keys(), and items() are essential.
  • Dictionary comprehensions can build dicts from iterables (advanced topic).

Happy coding!

Comments