Python dictionaries are versatile, unordered collections of key-value pairs. They provide an efficient way to store and retrieve data using unique keys.
To create a dictionary, use curly braces {}
or the dict()
constructor. Keys and values are separated by colons, while pairs are separated by commas.
# Using curly braces
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
# Using dict() constructor
another_dict = dict(name="Bob", age=25, city="London")
Access dictionary values using their corresponding keys. You can also modify existing values or add new key-value pairs.
# Accessing values
print(my_dict["name"]) # Output: Alice
# Modifying values
my_dict["age"] = 31
# Adding new key-value pairs
my_dict["occupation"] = "Engineer"
Python provides several built-in methods for working with dictionaries:
get()
: Safely retrieve valueskeys()
: Return all keysvalues()
: Return all valuesitems()
: Return key-value pairs as tuplespop()
: Remove and return a valueCreate dictionaries efficiently using dictionary comprehension, similar to Python List Comprehension.
squares = {x: x**2 for x in range(5)}
# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Dictionaries are ideal for:
When working with dictionaries, keep these tips in mind:
in
operator to check for key existencedefaultdict
for handling missing keysTo deepen your understanding of Python data structures, explore these related topics:
Mastering dictionaries is crucial for efficient data manipulation in Python. They offer a powerful way to organize and access information, making them indispensable in many programming scenarios.