When you’re learning Python, dictionaries are one of the most important data structures you’ll encounter. Unlike lists (see blog post) which store items by position, dictionaries store data as key-value pairs, making them the natural choice whenever you need to look something up by name rather than by index.
In this post, we’ll cover everything you need to know about Python dictionaries: what they are, how they work, and how to use them effectively.

What is a Python Dictionary?

A Python dictionary is a mutable, ordered, key-value collection. Think of it like a real dictionary; you look up a word (the key) to find its definition (the value).
Mutable – Items can be changed after the dictionary has been created.
Ordered – Dictionaries maintain insertion order (Python 3.7+).
Key-value pairs – Every item consists of a unique key and an associated value.
Keys must be unique and are immutable, values don’t have to be.

Creating a dictionary

Dictionaries can be created using curly brackets {} with key: value pairs, or by calling the dict() constructor.

Accessing items

Access values using dictionary[key] or the safer get() method.
Using dictionary[key] will raise a KeyError if the key doesn’t exist. Using get() returns None by default, or a fallback value you specify. It’s the safer choice when you’re not sure a key is present.

Adding & updating items

Dictionaries are mutable, so items can be added or updated directly by assigning to a key. The update() method lets you add or update multiple items at once.

Removing items

Items can be removed from dictionaries using pop(), popitem(), and clear().

Finding & checking items

Use the keyword ‘in’ to check whether a key exists. The get() method (covered earlier) is also useful for safe lookups.

Looping around dictionaries

Dictionaries support several iteration patterns. By default, looping over a dictionary iterates over its keys.

Dictionary comprehensions

Dictionary comprehensions allow you to create new dictionaries using less code.

Nested dictionaries

Dictionaries can contain other dictionaries as values, which is useful for representing hierarchical or structured data.

 

Conclusion

Python dictionaries are one of the most powerful and widely used data structures. Their key-value structure makes them the natural fit for many datasets including: API responses, JSON, row mappings and many more. By knowing how to create, access, update and loop through dictionaries, you’ll have a tool that you’ll reach for constantly across your Python work. Lists are about storing items in order, dictionaries are about storing items you need to find by name.

Tags: , , , ,