0% found this document useful (0 votes)
4 views

# Dictionaries in Python

Dictionaries in Python are key-value pair data structures that are mutable, unordered, and optimized for fast lookups. They allow for efficient data storage and retrieval, supporting various operations such as adding, updating, and removing elements. Common use cases include structured data records, fast lookups, and caching results.

Uploaded by

MUKUL CHAUHAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

# Dictionaries in Python

Dictionaries in Python are key-value pair data structures that are mutable, unordered, and optimized for fast lookups. They allow for efficient data storage and retrieval, supporting various operations such as adding, updating, and removing elements. Common use cases include structured data records, fast lookups, and caching results.

Uploaded by

MUKUL CHAUHAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

# 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 with initial values


person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Using dict() constructor


person = dict(name='Alice', age=30, city='New York')

# From list of tuples


pairs = [('name', 'Bob'), ('age', 25)]
person = dict(pairs)

# Dictionary comprehension
squares = {x: x*x for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
```

## Accessing Dictionary Elements

```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)

# Get all keys, values, or items


keys = person.keys() # dict_keys(['name', 'age', 'city'])
values = person.values() # dict_values(['Alice', 30, 'New York'])
items = person.items() # dict_items([('name', 'Alice'), ...])
```

## 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

# Update multiple values


person.update({'age': 32, 'country': 'USA'})

# 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

# Iterating through dictionary


for key in person: # Iterate keys
print(key, person[key])

for key, value in person.items(): # Iterate key-value pairs


print(key, value)

# Dictionary merging (Python 3.9+)


dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2 # {'a': 1, 'b': 3, 'c': 4}
```

## Dictionary Methods

| Method | Description | Example |


|--------|-------------|---------|
| `get(key[, default])` | Safe value retrieval | `value = d.get('x', 0)` |
| `setdefault(key[, default])` | Get value or set default | `d.setdefault('x', [])` |
| `update([other])` | Merge dictionaries | `d1.update(d2)` |
| `pop(key[, default])` | Remove and return value | `value = d.pop('x')` |
| `popitem()` | Remove and return last item | `k, v = d.popitem()` |
| `clear()` | Remove all items | `d.clear()` |
| `copy()` | Shallow copy | `new = d.copy()` |

## Common Use Cases

1. **Structured data records**: Representing objects with named fields


2. **Fast lookups**: O(1) average time complexity for operations
3. **Counting occurrences**: Using dictionary as frequency counter
4. **Caching/memoization**: Storing computed results
5. **JSON-like data structures**: Working with APIs and configurations

```python
# Frequency counter example
text = "apple banana apple orange banana apple"
words = text.split()
count = {}

for word in words:


count[word] = count.get(word, 0) + 1

# {'apple': 3, 'banana': 2, 'orange': 1}


```

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy