Skip to main content

📝 Latest Blog Post

Python Dictionaries: A Guide to Key-Value Data

Python Dictionaries: A Guide to Key-Value Data

When you need to store data in a way that is not sequential but is instead based on unique identifiers, Python's **dictionaries** are the perfect data structure. A dictionary is an unordered collection of items, where each item consists of a **key** and a **value**. The key acts as the unique identifier, allowing you to quickly and easily retrieve the corresponding value. Dictionaries are incredibly versatile and are used everywhere, from storing user information to configuring application settings.

Creating and Accessing Dictionaries

Dictionaries are defined using curly braces `{}` and a colon `:` to separate each key from its value. Each key-value pair is separated by a comma.

# A simple dictionary
user_profile = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Accessing a value by its key
print(user_profile["name"])  # Output: Alice

You can also use the `.get()` method to access values, which is safer because it doesn't throw an error if the key doesn't exist.

# Using .get() for safer access
print(user_profile.get("country", "Not Found"))  # Output: Not Found

Modifying and Looping Through Dictionaries

Dictionaries are mutable, which means you can add, remove, or modify items after they've been created. Adding a new key-value pair is as simple as assigning a value to a new key.

# Adding a new key-value pair
user_profile["occupation"] = "Developer"

# Looping through a dictionary
for key, value in user_profile.items():
    print(f"{key}: {value}")

The `.items()` method returns a view of the dictionary's key-value pairs, which is perfect for looping. By understanding how to create, access, and modify dictionaries, you'll be able to work with a wide range of data in Python and write more efficient and readable code.

Comments

đź”— Related Blog Post

🌟 Popular Blog Post