### Python Dictionaries in Depth
Python dictionaries are a core data structure in Python used to store key-value pairs. They are similar to hash tables or associative arrays in other programming languages.
#### Key-Value Pairs
– **Keys**: Immutable types like strings, numbers, or tuples. Keys must be unique within a dictionary.
– **Values**: Any data type can be used as a value.
#### Basic Operations
1. **Creation**: You create dictionaries using curly braces `{}` or the `dict()` function.
“`python
# Using curly braces
fruits = {‘apple’: 2, ‘banana’: 3, ‘orange’: 5}
# Using dict function
car = dict(make=’Toyota’, model=’Camry’, year=2020)
“`
2. **Insertion**: Add new key-value pairs using indexing.
“`python
fruits[‘grape’] = 10
“`
3. **Updating**: You can update existing entries by reassigning their values.
“`python
fruits[‘apple’] = 4 # Updates the value of ‘apple’ to 4
“`
4. **Deleting**: Remove elements using `del`, `pop()`, or `popitem()`.
“`python
# Using del statement
del fruits[‘banana’] # Removes ‘banana’: 3
# Using pop method
oranges = fruits.pop(‘orange’) # Removes ‘orange’: 5 and returns 5
# Using popitem method for arbitrary removal
item = fruits.popitem() # Removes and returns the last item, since Python 3.7+
“`
#### Nested Dictionaries
Dictionaries can contain dictionaries as their values, allowing you to create complex, hierarchical data structures.
“`python
person = {
‘name’: ‘John Smith’,
‘age’: 30,
‘address’: {
‘street’: ‘123 Main St’,
‘city’: ‘Anytown’,
‘zip’: ‘12345’
},
‘children’: [
{‘name’: ‘Jane’, ‘age’: 10},
{‘name’: ‘Doe’, ‘age’: 12}
]
}
“`
#### Iteration
– **Keys**: Use the `keys()` method or directly iterate over the dictionary.
“`python
for key in fruits.keys():
print(key)
“`
– **Values**: Use the `values()` method.
“`python
for value in fruits.values():
print(value)
“`
– **Items**: Use the `items()` method to get key-value pairs.
“`python
for key, value in fruits.items():
print(f”{key}: {value}”)
“`
#### Real-World Examples
1. **JSON Data Parsing**: JSON (JavaScript Object Notation) is frequently parsed into dictionaries in Python.
“`python
import json
json_data = ‘{“name”: “Alice”, “age”: 25, “city”: “New York”}’
data = json.loads(json_data) # Converts JSON string to a dictionary
print(data[‘name’]) # Output: Alice
“`
2. **Caching**: Dictionaries are often used to implement caches due to their fast lookup times.
“`python
# A simple example of a cache
cache = {}
def get_from_cache(key):
if key in cache:
return cache[key]
result = expensive_operation(key) # Placeholder for a time-consuming operation
cache[key] = result
return result
“`
3. **Configuration Handling**: Configuration settings can be stored in dictionaries, making it easy to manage application settings.
“`python
config = {
‘database’: {
‘host’: ‘localhost’,
‘port’: 5432
},
‘debug’: True
}
if config[‘debug’]:
print(“Debug mode is on”)
“`
### Conclusion
Python dictionaries are versatile and powerful due to their flexible structure, enabling them to store complex datasets. They allow fast data retrieval and are widely used in scenarios such as JSON parsing, caching, and configuration handling. Understanding how to effectively use dictionaries is a fundamental aspect of Python programming.