Python Dictionaries
1. Creating Dictionaries:
# Empty dictionary
empty_dict = {}
# Dictionary with key-value pairs
person = {'name': 'John', 'age': 30, 'city': 'New York'}
2. Accessing Values:
# Values in a dictionary are accessed using square brackets [] with the key
person = {'name': 'John', 'age': 30, 'city': 'New York'}
name = person['name'] # 'John'
3. Modifying Values:
# You can modify the value associated with a key
person = {'name': 'John', 'age': 30, 'city': 'New York'}
person['age'] = 31
# Now, person is {'name': 'John', 'age': 31, 'city': 'New York'}
4. Adding New Items:
# You can add new key-value pairs to a dictionary
person = {'name': 'John', 'age': 30, 'city': 'New York'}
person['occupation'] = 'Engineer'
# Now, person is {'name': 'John', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}
5. Removing Items:
# You can remove a key-value pair from a dictionary using the del statement or the pop() method
person = {'name': 'John', 'age': 30, 'city': 'New York'}
del person['age']
# or
age = person.pop('age')
# Now, person is {'name': 'John', 'city': 'New York'}, and age contains the removed value (30)
6. Checking Membership:
# You can check if a key is present in a dictionary using the in and not in operators
person = {'name': 'John', 'age': 30, 'city': 'New York'}
has_age = 'age' in person # True
7. Dictionary Methods:
# Dictionaries have various methods, including keys(), values(), and items()
person = {'name': 'John', 'age': 30, 'city': 'New York'}
keys_list = person.keys() # Returns a list of keys
values_list = person.values() # Returns a list of values
items_list = person.items() # Returns a list of key-value pairs as tuples
8. Nested Dictionaries:
# Dictionaries can be nested, allowing you to create more complex data structures
students = {
'Alice': {'age': 25, 'grade': 'A'},
'Bob': {'age': 22, 'grade': 'B'}
}
Dictionaries are versatile data structures that provide a way to store and retrieve data based on keys. They are commonly used in various programming scenarios, such as representing configurations, JSON data, or any situation where a mapping between keys and values is required.