Browse Courses

Dictionaries

This document explains Python dictionaries, including keys, values, creation access, modification, deletion, and methods for managing key-value pairs.

This document covers Python dictionaries, including keys, values, creation, access, modification, deletion, and methods for managing key-value pairs efficiently.


Introduction

Dictionaries are collections in Python that store data as key-value pairs. Keys are unique and immutable, while values can be mutable or immutable.


Creating and Accessing Dictionaries

  • Create a dictionary with curly brackets {}.
  • Keys must be unique and immutable (often strings).
  • Values can be any type and may be duplicated.

Example:

1album_release = {
2    "Back in Black": 1980,
3    "The Dark Side of the Moon": 1973,
4    "The Bodyguard": 1992
5}

Access values using keys:

1album_release["Back in Black"]  # 1980
2album_release["The Dark Side of the Moon"]  # 1973

Modifying Dictionaries

  • Add a new entry: album_release["Graduation"] = 2007
  • Delete an entry: del album_release["Thriller"]
  • Check if a key exists: "Back in Black" in album_release (returns True or False)

Dictionary Methods

  • Get all keys: album_release.keys()
  • Get all values: album_release.values()

Visualizing Dictionaries

Dictionaries can be visualized as tables:

KeyValue
Back in Black1980
The Dark Side of the Moon1973
The Bodyguard1992

Conclusion

Python dictionaries provide a flexible way to store and manage key-value pairs. Understanding creation, access, modification, and methods is essential for efficient data handling.


FAQ

A dictionary is a collection of key-value pairs, where keys are unique and immutable, and values can be any type.

The previous value for that key will be overwritten by the new value, as keys must be unique.

  1. Adding a new key-value pair
  2. Deleting a key-value pair
  3. Accessing a value by key
  4. Accessing a value by index
(4) Dictionaries do not support access by index; values are accessed by key.

The keys() method returns a list-like object containing all the keys in the dictionary.

ConceptDescription
A. Key1. Information associated with a key
B. Value2. Unique, immutable identifier in a dictionary
C. Del3. Removes a key-value pair
D. In4. Checks if a key exists
A-2, B-1, C-3, D-4.

Dictionary values can be mutable, immutable, and duplicated, but keys must be unique and immutable.

True. Keys must be unique and immutable; values can be any type and duplicated.

Ensure the key is unique and immutable to avoid overwriting existing values or errors.

The values() method is used to get all values from a dictionary.

Values are accessed using keys, not indexes, making dictionaries suitable for fast lookups.

Deleting a key removes both the key and its associated value from the dictionary.