About Lesson
Key-Value Pairs, Accessing, and Modifying
- Definition: A dictionary is an unordered collection of key-value pairs. Keys must be unique and immutable, while values can be of any data type.
- Creating Dictionaries: python
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
- Accessing Values: Use the key to access the corresponding value. python
print(my_dict['name']) # Output: Alice
- Modifying Values: Assign a new value to a specific key. python
my_dict['age'] = 26 print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
- Adding Key-Value Pairs: Simply assign a value to a new key. python
my_dict['email'] = 'alice@example.com' print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
- Removing Key-Value Pairs: Use
del
to remove a key-value pair. pythondel my_dict['city'] print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}