Introduction

Dictionaries are a versatile and widely used data structure in Python. They allow you to store data in key-value pairs, making it easy to retrieve and manipulate information. In this guide, we'll explore how to work with Python dictionaries and perform various operations using sample code.


Creating Dictionaries

Dictionaries are created using curly braces {}, and key-value pairs are separated by colons. For example:

# Creating a dictionary
person = {
"first_name": "John",
"last_name": "Doe",
"age": 30,
"city": "New York"
}

Accessing Dictionary Items

You can access dictionary values by referring to their keys. For example:

# Accessing dictionary items
first_name = person["first_name"]
age = person["age"]

Modifying Dictionaries

You can add, update, or remove items in a dictionary using various methods and operations. For example:

# Modifying dictionaries
person["occupation"] = "Engineer" # Adding a new key-value pair
person["age"] = 35 # Updating an existing value
del person["city"] # Removing a key-value pair

Iterating Through Dictionaries

You can iterate through the keys, values, or items (key-value pairs) of a dictionary using loops. For example:

# Iterating through dictionaries
for key in person:
print(key, person[key])
for value in person.values():
print(value)
for key, value in person.items():
print(key, value)

Checking if a Key Exists

You can check if a key exists in a dictionary using the in keyword. For example:

# Checking if a key exists
if "first_name" in person:
print("Key 'first_name' exists in the dictionary")

Conclusion

Python dictionaries are powerful for storing and manipulating data in a structured way. Understanding how to create, access, modify, and iterate through dictionaries is essential for many Python applications, including data handling and management.