Skip to main content

What are dictionaries?

Dictionaries store data in key-value pairs. Think of them like a real dictionary where you look up a word (key) to find its definition (value). Real-world examples:
  • Phone book: name > phone number
  • Menu: dish > price
  • User profile: username > user info

Creating Dictionaries

Python provides several ways to create dictionaries depending on your data source and style:

1. Using Literal Curly Braces {}

The most common way to create a dictionary is using curly braces with key-value pairs separated by colons:

2. Using the dict() Constructor

You can construct dictionaries using the built-in dict() constructor in two ways:
  • Keyword arguments: Keys are passed as keyword arguments (keys are automatically converted to strings):
  • List of key-value tuples: Useful when converting zipped or tabular sequences into a dictionary:

3. Using dict.fromkeys()

Useful when you want to initialize a dictionary with a set of keys mapping to the same default value:

4. Dictionary Comprehension

A concise way to construct dictionaries dynamically using loops:
Keys must be unique and of an immutable type (like strings, numbers, or tuples). Values can be of any data type and can repeat.

Accessing values

Changing dictionaries

Dictionary methods

Nested dictionaries

Common mistakes

Practice & Exercises

To reinforce what you’ve learned in this section (Dictionaries, creation patterns, key accesses, and updates), practice with these interactive notebooks:

Follow-Along Practice

Practice initializing dictionaries in various ways, looking up values, and editing key-value pairs.💻 VS Code | 🚀 Colab | 📥 Download

Practice Exercises

Test your knowledge with hands-on exercises on school grades databases and safe lookups.💻 VS Code | 🚀 Colab | 📥 Download

What’s next?

Finally, let’s explore Sets - collections of unique items!

Sets

Learn about unique values