Dictionaries
Understanding Dictionaries
A dictionary in Python is an unordered collection of key-value pairs. It's similar to a real-world dictionary where you look up a word (key) to find its meaning (value). Dictionaries are defined by enclosing key-value pairs within curly braces {}.
Creating a Dictionary
Python
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
In this example, 'name', 'age', and 'city' are keys, and their corresponding values are 'Alice', 30, and 'New York'.
Accessing Dictionary Elements
You can access values using their corresponding keys:
Python
my_dict = {'name': 'Alice', 'age': 30}
name = my_dict['name'] # Accessing the value associated with the key 'name'
print(name) # Output: Alice
Modifying Dictionaries
Dictionaries are mutable, so you can change, add, or remove key-value pairs:
Python
my_dict = {'name': 'Alice', 'age': 30}
my_dict['age'] = 31 # Modifying the value of an existing key
my_dict['city'] = 'Los Angeles' # Adding a new key-value pair
del my_dict['age'] # Removing a key-value pair
Dictionary Methods
Python provides several methods for working with dictionaries:
- keys(): Returns a view of the dictionary's keys.
- values(): Returns a view of the dictionary's values.
- items(): Returns a view of the dictionary's key-value pairs as tuples.
- get(key, default): Returns the value for the specified key. If the key is not found, returns the default value (None if not specified).
- pop(key, default): Removes and returns the value for the specified key. If the key is not found, returns the default value (raises a KeyError if not specified).
- update(other_dict): Updates the dictionary with the key-value pairs from another dictionary.
Example
Python
my_dict = {'name': 'Alice', 'age': 30}
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
print(keys) # Output: dict_keys(['name', 'age'])
print(values) # Output: dict_values(['Alice', 30])
print(items) # Output: dict_items([('name', 'Alice'), ('age', 30)])
Important Points
- Dictionary keys must be immutable (e.g., strings, numbers, tuples).
- Dictionaries are unordered, meaning the order of elements is not guaranteed.
- Dictionaries are efficient for lookups based on keys.
Dictionaries are a powerful data structure in Python, widely used for representing data with key-value relationships