# Dictionaries in Python
# Dictionaries in Python
Dictionaries are one of Python's most powerful and commonly used data structures. They store
data as **key-value pairs**, providing efficient lookup, insertion, and deletion operations.
## Characteristics of Dictionaries
1. **Unordered** (Python 3.7+ maintains insertion order, but should not be relied upon for logic)
2. **Mutable** - can be modified after creation
3. **Keys must be unique** - no duplicate keys allowed
4. **Keys must be immutable** (strings, numbers, tuples)
5. **Values can be any type** and can be duplicated
6. **Highly optimized** for fast lookups by key
## Creating Dictionaries
```python
# Empty dictionary
empty_dict = {}
empty_dict = dict()
# Dictionary comprehension
squares = {x: x*x for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```
```python
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Access by key
print(person['name']) # 'Alice'
# Using get() - safer (returns None if key doesn't exist)
print(person.get('age')) # 30
print(person.get('country')) # None
print(person.get('country', 'USA')) # 'USA' (default value)
## Modifying Dictionaries
```python
person = {'name': 'Alice', 'age': 30}
# Adding/updating elements
person['city'] = 'New York' # Add new key-value
person['age'] = 31 # Update existing key
# Removing elements
del person['city'] # Remove key
age = person.pop('age') # Remove and return value
person.clear() # Empty the dictionary
```
## Common Operations
```python
# Check if key exists
if 'name' in person:
print(person['name'])
# Length of dictionary
print(len(person)) # Number of key-value pairs
## Dictionary Methods
```python
# Frequency counter example
text = "apple banana apple orange banana apple"
words = text.split()
count = {}
Dictionaries are fundamental to Python programming and are optimized for performance.
They're used extensively in Python programs and are often the best choice for storing and
accessing data by unique keys.