Back to PYTHON FUNDAMENTALS

Python Dictionaries

Learn how to store key–value data using dictionaries and why they are essential for storing structured information.

8 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. Defining Dictionaries — Dictionaries are ordered, changeable collections of unique key-value pairs enclosed in curly braces.
  2. Dictionary Creation — A dictionary named capitals is created mapping countries (keys) to their capitals (values).
  3. Safe Value Retrieval — The dict.get(key) method retrieves a value and returns None if the key is not found, preventing errors.
  4. Adding and Updating — The dict.update() method is used to insert a new key-value pair or change the value of an existing key.
  5. Removing Entries — Key-value pairs are removed using dict.pop(key) for a specific entry or dict.popitem() for the latest entry.
  6. Iterating Keys — The dict.keys() method returns an iterable view of all keys, which can be used in a for loop.
  7. Iterating Values — The dict.values() method returns an iterable view of all values, allowing iteration over only the values.
  8. Iterating Items — The dict.items() method returns key-value pairs as tuples, enabling simultaneous iteration over both components.
PDF notes

Frequently asked questions

Can a dictionary have duplicate values?

Yes, multiple unique keys can point to the same value, but each key itself must be unique within the dictionary.

Why does `dict.keys()` return an object that resembles a list?

It returns a dynamic view object that reflects changes made to the dictionary, unlike a static list copy.

How do I check if a key exists in the dictionary?

Use the `get()` method and check if the result is not `None`, or use the faster `key in dictionary` syntax.

What happens if I use `update()` with a key that already exists?

The value associated with that existing key will be overwritten by the new value provided in the update.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.