Skip to main content

1. What is a Dictionary?

  • A dictionary is a collection of key-value pairs that are unordered, mutable (changeable), and indexed by keys.
  • Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any type.
  • Dictionaries are defined using curly braces {} or the dict() constructor.
Example:

2. Dictionary Operations

1. Accessing Values

  • Use the key to access the corresponding value.
  • If the key does not exist, it raises a KeyError. Use the get() method to avoid this.
Examples:

2. Adding/Updating Elements

  • Add a new key-value pair or update an existing one using the assignment operator =.
Example:

3. Removing Elements

  • Use pop() to remove a key-value pair by key (returns the value).
  • Use popitem() to remove the last inserted key-value pair (Python 3.7+).
  • Use del to delete a key-value pair.
  • Use clear() to remove all key-value pairs.
Examples:

4. Checking for Keys

  • Use the in keyword to check if a key exists in the dictionary.
Example:

5. Iterating Over a Dictionary

  • Use loops to iterate over keys, values, or key-value pairs.
Examples:

6. Length

  • Use len() to find the number of key-value pairs in a dictionary.
Example:

3. Dictionary Methods

1. keys()

  • Returns a view of all keys in the dictionary.
Example:

2. values()

  • Returns a view of all values in the dictionary.
Example:

3. items()

  • Returns a view of all key-value pairs as tuples.
Example:

4. update()

  • Merges another dictionary into the current one (updates existing keys and adds new ones).
Example:

5. copy()

  • Returns a shallow copy of the dictionary.
Example:

4. Dictionary Comprehensions

  • A concise way to create dictionaries using a single line of code.
  • Syntax: {key: value for item in iterable}
Example:

5. Nested Dictionaries

  • A dictionary can contain other dictionaries, creating a multi-level structure.
Example:

6. Additional Examples

  • Creating a Dictionary:
  • Adding/Updating Elements:
  • Removing Elements:
  • Iterating Over a Dictionary:
  • Dictionary Comprehension:

7. Best Practices

  • Use meaningful keys to make dictionaries easy to understand.
  • Use get() to avoid KeyError when accessing keys that may not exist.
  • Use dictionary comprehensions for concise and readable code.