fbpx

Dictionaries in Python

A dictionary in Python is a collection of key-value pairs, where each key must be unique. Dictionaries are versatile and allow efficient data retrieval based on keys. They are defined using curly braces {} and the key-value pairs separated by colons. Here’s an overview of dictionaries and their common operations:

Creating Dictionaries:

# Creating an empty dictionary
empty_dict = {}

# Creating a dictionary with key-value pairs
my_dict = {"name": "John", "age": 25, "city": "New York"}

Accessing Values:

You can access values in a dictionary using keys.

# Accessing values
name = my_dict["name"]
age = my_dict["age"]

Modifying and Adding Key-Value Pairs:

Dictionaries are mutable, allowing you to modify values and add new key-value pairs.

# Modifying values
my_dict["age"] = 26

# Adding new key-value pairs
my_dict["gender"] = "Male"

Removing Key-Value Pairs:

You can use the del keyword to remove a key-value pair.

# Removing a key-value pair
del my_dict["city"]

Dictionary Methods:

Dictionaries come with several built-in methods for common operations.

# Getting keys and values
keys = my_dict.keys()
values = my_dict.values()

# Checking if a key is in the dictionary
is_present = "age" in my_dict

# Getting the value for a key with a default value
age = my_dict.get("age", 0)

Iterating Through a Dictionary:

You can use loops to iterate through the keys, values, or items (key-value pairs) of a dictionary.

# Iterating through keys
for key in my_dict:
    print(key)

# Iterating through values
for value in my_dict.values():
    print(value)

# Iterating through items
for key, value in my_dict.items():
    print(f"{key}: {value}")

Dictionary Comprehensions:

Similar to list comprehensions, you can use dictionary comprehensions to create dictionaries in a concise manner.

# Creating a dictionary using comprehension
squares = {x: x**2 for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Nested Dictionaries:

Dictionaries can be nested, allowing for more complex data structures.

nested_dict = {
    "person": {
        "name": "Alice",
        "age": 30,
        "address": {"city": "Wonderland", "zipcode": "12345"}
    },
    "company": {
        "name": "Tech Corp",
        "employees": 1000
    }
}

Dictionary Views:

Dictionary views provide dynamic views of the dictionary’s keys, values, or items.

# Dictionary view of keys
key_view = my_dict.keys()

# Dictionary view of values
value_view = my_dict.values()

# Dictionary view of items
item_view = my_dict.items()

Dictionaries are widely used in Python for tasks involving mappings, configurations, and data retrieval based on unique keys. Their flexibility and efficiency make them an essential data structure in many Python applications.