Python Dictionaries

Accessing and modifying elements

1. Accessing values by key:

To retrieve the value associated with a specific key in a dictionary, you use square brackets [] after the dictionary name, followed by the key you want to access:

my_dict = {"name": "Charlie", "age": 40, "city": "Los Angeles"}

# Accessing the value for key "name"
name = my_dict["name"]
print(name)  # Output: Charlie

If you try to access a key that doesn't exist in the dictionary, Python will raise a KeyError. To avoid this, you can use the get() method (explained later).


2.Modifying existing values:

To change the value associated with an existing key, use the same syntax as accessing values, but assign a new value to the key:

my_dict["age"] = 42  # Update the age value

print(my_dict)  # Output: {'name': 'Charlie', 'age': 42, 'city': 'Los Angeles'}


3.Adding new key-value pairs:

To add a new entry to a dictionary, use the same square bracket syntax, but provide a new key that doesn't exist yet and assign its corresponding value:

my_dict["occupation"] = "Software Engineer"

print(my_dict)  # Output: {'name': 'Charlie', 'age': 42, 'city': 'Los Angeles', 'occupation': 'Software Engineer'}


4. Additional considerations:

  • Remember that dictionaries are mutable, meaning you can modify their contents after creation.
  • Keys must be unique and immutable (cannot be changed) to maintain the integrity of the key-value association.
  • It's generally considered good practice to avoid modifying dictionary elements while iterating through them using a loop, as it can lead to unexpected behavior.

5. Alternative for Safe access: get() Method:

The get(key, default=None) method is a safer way to access values in a dictionary. It takes two arguments:

  • key: The key you want to retrieve the value for.
  • default (optional): A default value to return if the key doesn't exist.

value = my_dict.get("occupation", "Not specified")  # Returns "Software Engineer"

# If the key doesn't exist, returns "Not specified"
nonexistent_key = my_dict.get("country", "N/A")

By using get(), you can avoid potential KeyError exceptions and provide a meaningful default value if the key is missing.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

How do you access the value associated with a specific key in a dictionary?

Using the get() method
Using parentheses ()
Using square brackets []
Using curly braces {}
Check Answer

How do you modify the value of an existing key in a dictionary?

By using the square brackets and assigning a new value
By using the update() method
By using the append() method
By directly calling the key
Check Answer

How do you add a new key-value pair to a dictionary?

Using the dict.update() method
Using the add() method
Using square brackets with an existing key
Using square brackets with a new key
Check Answer

What does the get() method do when the specified key does not exist?

Raises a KeyError
Returns a default value
Returns None
Returns an empty string
Check Answer

What is true about dictionaries in Python?

Values must be unique
Dictionaries maintain order
Dictionaries are mutable
Keys must be mutable
Check Answer