Learn Python
- Python basic
- Introduction to File Handling
- Basics of List Comprehension
- Introduction to Matplotlib
- Classes and Objects
- Introduction to Functions
- Python Numbers
- Creating Basic Plots
- Opening and closing files
- Function parameters and arguments
- Advanced Techniques
- Attributes and Methods
- Python Strings
- Scope and lifetime of variables
- Advanced Plotting
- Reading from files
- Performance and Limitations
- Encapsulation
- Python List
- Specialized Plots
- Writing to files
- Return statement and output
- Inheritance
- Python Tuple
- Advanced Customization
- Working with different file formats
- Lambda Functions
- Polymorphism
- Practical Applications
- Higher-Order Functions
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?
AUsing parentheses ()
BUsing square brackets []
CUsing curly braces {}
DUsing the get() method
Check Answer
How do you modify the value of an existing key in a dictionary?
CBy using the append() method
DBy directly calling the key
ABy using the square brackets and assigning a new value
BBy using the update() method
Check Answer
How do you add a new key-value pair to a dictionary?
AUsing the add() method
BUsing square brackets with an existing key
CUsing square brackets with a new key
DUsing the dict.update() method
Check Answer
What does the get() method do when the specified key does not exist?
CReturns None
DReturns an empty string
ARaises a KeyError
BReturns a default value
Check Answer
What is true about dictionaries in Python?
ADictionaries are mutable
BKeys must be mutable
CValues must be unique
DDictionaries maintain order
Check Answer