Python Dictionaries

A dictionary in Python is an unordered collection of data in the form of key-value pairs. It is one of the most powerful and flexible data structures in Python. Dictionaries are defined by enclosing a comma-separated list of key-value pairs within curly braces {}. Each key-value pair is separated by a colon :.

Definition and Characteristics of Dictionaries

Let's see how to create a basic dictionary in Python:

Example 1: Creating a Dictionary


# Example: Creating a Dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print("Dictionary:", person)
        

Output

Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Accessing Values in a Dictionary

You can access the values in a dictionary by referring to their keys:


# Example: Accessing Dictionary Values
print("Name:", person["name"])
print("Age:", person.get("age"))
        

Output

Name: Alice Age: 25

Modifying a Dictionary

You can add new items or change existing ones by using the assignment operator:

Example: Modifying a Dictionary


person["age"] = 26  # Modifying existing value
person["email"] = "alice@example.com"  # Adding a new key-value pair
print("Updated Dictionary:", person)
        

Output

Updated Dictionary: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}

Deleting Items from a Dictionary

Dictionaries allow you to remove items using the del keyword or the pop() method:


del person["city"]  # Deleting an item by key
removed_email = person.pop("email", "Not Found")  # Removing with pop()
print("After Deletion:", person)
print("Removed Email:", removed_email)
        

Output

After Deletion: {'name': 'Alice', 'age': 26} Removed Email: alice@example.com

Looping Through a Dictionary

You can loop through a dictionary to access its keys, values, or both:


for key, value in person.items():
print(f"{key}: {value}")
        

Output

name: Alice age: 26

Common Dictionary Methods

Let's see how some of these methods work:

Using Dictionary Methods


person.update({"city": "Boston", "age": 27})
print("Updated Person:", person)
print("Keys:", list(person.keys()))
print("Values:", list(person.values()))
print("Items:", list(person.items()))
        

Output

Updated Person: {'name': 'Alice', 'age': 27, 'city': 'Boston'} Keys: ['name', 'age', 'city'] Values: ['Alice', 27, 'Boston'] Items: [('name', 'Alice'), ('age', 27), ('city', 'Boston')]

Dictionaries are an essential data structure in Python, offering a powerful way to store and manage data using key-value pairs. They are highly versatile and efficient for quick data lookups, modifications, and complex data manipulations. Understanding dictionaries and their methods is crucial for effective Python programming.