What Are Dictionaries in Python and How Do You Use Them?

Imagine you have a list of phone numbers, but instead of accessing them by a numeric index like 0 or 1, you want to look them up by a person’s name. This is exactly what a dictionary in Python is for! Dictionaries store data in key-value pairs, making them incredibly efficient for lookups.

🔑 Understanding Key-Value Pairs

Unlike a list, which is indexed by a sequence of numbers, a dictionary is indexed by keys. These keys can be strings, numbers, or other immutable types. Each key is associated with a value. Together, they form a key-value pair. You create a dictionary using curly braces {}, with each pair written as key: value. For example: phonebook = {"Alice": "555-1234", "Bob": "555-5678"}.

➕ Accessing, Adding, and Modifying Data

Accessing a value is simple: you use the key inside square brackets, much like a list index. For example, phonebook["Alice"] would return “555-1234”. Adding a new entry or modifying an existing one uses the same syntax. If the key doesn’t exist, a new key-value pair is created. If it does exist, the value is updated.
phonebook["Charlie"] = "555-9999" # Adds a new entry
phonebook["Alice"] = "555-4321" # Updates an existing entry

🔄 Looping Through a Dictionary

You can easily loop through a dictionary with a for loop. By default, looping over a dictionary gives you its keys.
for name in phonebook:
    print(name, phonebook[name])
If you only want to loop through the values, you can use the .values() method, like for number in phonebook.values():. This flexibility makes it easy to work with all the data stored inside.

Dictionaries are one of Python’s most important data structures. They are perfect for any situation where you need to store and retrieve data based on a unique identifier, rather than a simple position.

Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.

More Topics

Hello! I'm a gaming enthusiast, a history buff, a cinema lover, connected to the news, and I enjoy exploring different lifestyles. I'm Yaman Şener/trioner.com, a web content creator who brings all these interests together to offer readers in-depth analyses, informative content, and inspiring perspectives. I'm here to accompany you through the vast spectrum of the digital world.

Leave a Reply

Your email address will not be published. Required fields are marked *