Python Dictionaries
Dictionaries in Python are unordered collections of key-value pairs. They are useful for storing and retrieving data in a way that is efficient and easy to understand. In this lesson, we will cover the basics of dictionaries and how to work with them.
Creating Dictionaries
You can create a dictionary in Python by enclosing key-value pairs in curly braces {}
, with each pair separated by a colon :
. For example:
person = {'name': 'John', 'age': 30, 'gender': 'Male'}
scores = {'Math': 90, 'Science': 85, 'English': 88}
empty_dict = {}
Accessing Elements
You can access the value associated with a key in a dictionary by using the key inside square brackets[]
. For example:
print(person['name']) # Output: 'John'
print(scores['Math']) # Output: 90
Modifying and Adding Elements
You can modify the value associated with a key or add a new key-value pair to a dictionary by simply assigning a value to the key. For example:
person['age'] = 31 # Modify age
person['city'] = 'New York' # Add new key-value pair
Removing Elements
You can remove a key-value pair from a dictionary using the del
keyword or thepop()
method. For example:
del person['gender'] # Remove 'gender' key
removed_score = scores.pop('English') # Remove 'English' key and return its value
Conclusion
Dictionaries are a powerful data structure in Python for storing and retrieving data using keys. By understanding how to create, access, modify, and remove elements in dictionaries, you can effectively work with key-value pairs in your Python programs.