# counts == \{"apple": 2, "banana": 1, "orange": 1\}

- Canonical: https://33rdsquare.com/dictionaries-101-a-super-guide-for-a-dictionary-in-python/
- Published: 2024-09-03
- Author: Jordan Brown
- Categories: [Artificial Intelligence & Machine Learning & ChatGPT](https://33rdsquare.com/category/tech/ai/)

---

Welcome, Pythonista! If you‘re looking to level up your Python programming skills, you‘ve come to the right place. In this comprehensive guide, we‘ll dive deep into one of Python‘s most powerful and versatile data structures: the dictionary.

By the end of this article, you‘ll be a dictionary master, able to wield this mighty tool to solve complex problems and write more efficient, readable code. So let‘s jump right in!

## What are Python Dictionaries?

In the simplest terms, a dictionary is a collection of key-value pairs. Each key maps to a corresponding value, allowing you to quickly retrieve data associated with that key.

Dictionaries are:

- Unordered – items are not stored in a particular order
- Mutable – you can add, remove, and change items after creation
- Dynamic – dictionaries can grow and shrink in size as needed

Some common uses for dictionaries include:

- Storing structured data, like a user profile with name, email, etc.
- Counting the frequencies of items, words, etc.
- Building lookup tables to map codes to names
- Caching expensive computations for fast retrieval

Dictionaries are incredibly flexible – you‘ll find yourself using them in almost every non-trivial Python program you write!

## Dictionary Syntax and Structure

Dictionaries are created by enclosing comma-separated key-value pairs inside curly braces { }. Here‘s the basic syntax:

```

my_dict = {key1: value1, key2: value2, key3: value3}
```

Some important things to note about dictionary keys and values:

- Keys must be unique – no duplicate keys allowed
- Keys must be immutable types like strings, numbers, or tuples
- Values can be of any type – immutable, mutable, even other dictionaries
- Keys and values are separated by a colon :
- Key-value pairs are separated by commas

Here are a few examples of valid dictionaries:

```

empty_dict = {}
person = {"name": "Alice", "age": 32, "email": "alice@example.com"}
word_counts = {"the": 124, "and": 89, "python": 34}
```

## Creating Dictionaries

In addition to the { } syntax shown above, there are a few other ways to create dictionaries in Python.

You can use the dict() constructor function to create a dictionary from a list of key-value tuples:

```

items = [("name", "Alice"), ("age", 32), ("email", "alice@example.com")]
person = dict(items)
```

Or use keyword arguments to pass in keys and values:

```

person = dict(name="Alice", age=32, email="alice@example.com")
```

Python 3.5 introduced the concept of "dictionary unpacking" which allows you to merge multiple dictionaries:

```

defaults = {"role": "user", "active": True}
person = {**defaults, "name": "Alice"}
# person == {"role": "user", "active": True, "name": "Alice"}
```

As you can see, there‘s more than one way to build a dictionary in Python!

## Accessing and Modifying Dictionary Elements

To retrieve a value from a dictionary, simply use square brackets [] with the key:

```

person = {"name": "Alice", "age": 32}
name = person["name"]
print(name) # "Alice"
```

If the key doesn‘t exist, a KeyError is raised. You can avoid this by using the get() method which allows you to provide a default value:

```

email = person.get("email") # returns None
email = person.get("email", "") # default to empty string
```

Adding new key-value pairs or updating existing ones looks very similar:

```

person["email"] = "alice@example.com" # add new key-value pair
person["age"] = 33 # update existing value
```

To remove a key-value pair, use the del keyword:

```

del person["email"] # removes "email" key and value
```

## Common Dictionary Methods

Dictionaries come with many useful built-in methods. Here are some of the most commonly used ones:

- keys() – returns a view of all keys
- values() – returns a view of all values
- items() – returns a view of all key-value pairs as tuples
- get(key, default) – retrieve value for key, return default if missing
- pop(key, default) – remove and return value for key, return default if missing
- update(other_dict) – merge another dictionary into this one
- clear() – remove all items

For example, you can iterate over a dictionary‘s keys and values like this:

```

for key, value in person.items():
    print(key, value)
```

## Nested Dictionaries

Since dictionary values can be any type, it‘s common to see dictionaries nested inside other dictionaries.

For example, you might represent a collection of people like this:

```

people = {
    "alice": {
        "name": "Alice",
        "age": 32,
        "email": "alice@example.com"
    },
    "bob": {
        "name": "Bob",
        "age": 29
    }
}
```

To access nested values, simply chain the keys together:

```

alice_email = people["alice"]["email"]
bob_age = people["bob"]["age"]
```

Nested dictionaries are a powerful way to represent hierarchical or structured data in a compact format.

## Dictionaries vs Lists

Dictionaries and lists are two of the most commonly used data structures in Python. While they are both collections of items, they serve different purposes.

Use a list when:

- You need an ordered sequence of items
- You need to access items by position (index)
- You have homogeneous data (all items are the same type)

Use a dictionary when:

- You need to map keys to values
- You need fast lookup by key
- You have heterogeneous data (values of different types)

For example, use a list to store a sequence of numbers:

```

primes = [2, 3, 5, 7, 11]
print(primes[3]) # 7
```

But use a dictionary to map product codes to prices:

```

prices = {"apple": 0.5, "banana": 0.25, "orange": 0.75}
print(prices["banana"]) # 0.25
```

Understanding when to use a list vs a dictionary is an important skill to develop as you grow your Python expertise!

## Advanced Dictionary Techniques

Once you‘re comfortable with the dictionary basics, there are a number of more advanced techniques you can leverage.

Dictionary comprehensions allow you to concisely build dictionaries, similar to list comprehensions:

```

squares = {x: x*x for x in range(10)}
# squares == {0: 0, 1: 1, 4: 4, 9: 9, 16: 25, ...}
```

The merge | and update |= operators, introduced in Python 3.9, provide a cleaner syntax for combining dictionaries:

```

x = {"a": 1, "b": 2}
y = {"b": 3, "c": 4}
z = x | y # equivalent to z = {**x, **y}
x |= y # equivalent to x.update(y)
```

Python also provides some useful dictionary variants in the collections module:

- OrderedDict – maintains items in insertion order
- defaultdict – automatically initializes missing keys to a default

For example, defaultdict makes it easy to count items:

```

from collections import defaultdict
counts = defaultdict(int)
items = ["apple", "banana", "apple", "orange"]
for item in items:
counts[item] += 1
```

These are just a few of the more advanced techniques available. As you work on more complex projects, you‘ll find lots of opportunities to apply these tools!

## Real-World Dictionary Examples

To solidify your understanding, let‘s walk through a few real-world examples of dictionaries in action.

1. Counting word frequencies in a text document:

```

import string
def count_words(filename):
counts = defaultdict(int)
with open(filename) as file:
    for line in file:
        words = line.lower().translate(str.maketrans("", "", string.punctuation)).split()
        for word in words:
            counts[word] += 1

return counts

Building an inverted index to map words to the documents containing them:

def build_index(filenames):
    index = defaultdict(list)
for id, filename in enumerate(filenames):
    with open(filename) as file:
        for line in file:
            words = line.lower().split()
            for word in words:
                index[word].append(id)

return index

Memoizing expensive computations for fast lookup:

def fibonacci(n, cache=None):
    if cache is None:
        cache = {}
if n in cache:
    return cache[n]

if n <= 1:
    return n

cache[n] = fibonacci(n-1, cache) + fibonacci(n-2, cache)
return cache[n]
These examples demonstrate the versatility and power of dictionaries. With a little creativity, you can use them to solve all sorts of interesting problems!
Dictionary Best Practices
To wrap up, here are a few tips and best practices to keep in mind when working with dictionaries:
```

- Choose descriptive key names to make your code more readable
- Use defaultdict to handle missing keys gracefully
- Prefer get() over [] when retrieving values to avoid KeyErrors
- Use dictionary comprehensions for concise initialization
- Leverage the power of the collections module variants when appropriate

Remember, the more you practice using dictionaries in your own code, the more natural and intuitive they will become. Don‘t be afraid to experiment and try new things!

## Further Reading

There‘s always more to learn! If you want to deepen your dictionary expertise even further, here are a few resources to check out:

- Official Python documentation on dictionaries: [https://docs.python.org/3/library/stdtypes.html#mapping-types-dict](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)
- Dictionaries in Python video tutorial: [https://www.youtube.com/watch?v=XCcpzWs-CI4](https://www.youtube.com/watch?v=XCcpzWs-CI4)
- Python Dictionary Comprehension Tutorial: [https://www.datacamp.com/community/tutorials/python-dictionary-comprehension](https://www.datacamp.com/community/tutorials/python-dictionary-comprehension)
- Fluent Python book by Luciano Ramalho

I hope this guide has been helpful in your Python journey. Happy dictionary coding!

---

Source: [counts == \{"apple": 2, "banana": 1, "orange": 1\}](https://33rdsquare.com/dictionaries-101-a-super-guide-for-a-dictionary-in-python/)
