Lecture

Dictionaries: Keys and Values

In Python, a dictionary is a collection of key-value pairs that maps one item (the key) to another (the value).

In the example below, the keys represent fruits, and the values represent their corresponding numbers.

Creating a Dictionary
my_dict = { "apple": 1, "banana": 2, "cherry": 3 }

Dictionaries are useful when you need to store and retrieve data by a specific key.


Why Use Dictionaries?

Unlike lists, which access items by position, dictionaries retrieve data using keys.

This makes your code easier to read and maintain, especially when working with labeled information.

For instance, if you want to store details about a student, you can use a dictionary like this:

Student Dictionary
student = { "name": "Emily", "age": 22, "major": "Biology" }

In the example above, to retrieve the student's name, you would use student["name"].


Key Concepts

  • Each item in a dictionary is a pair of a key and a value.
  • Keys must be unique and immutable.
  • Values can be any type: numbers, strings, lists, or even other dictionaries.
  • Use dict[key] to retrieve or update a value.

When Are Dictionaries Useful?

Dictionaries are particularly useful when working with labeled data, such as user profiles, configuration settings, or grouped information.

They are also essential for handling JSON-like data and API responses.

Quiz
0 / 1

In Python dictionaries, keys must be unique and immutable.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result