3.3 Dictionaries

3.3 Dictionaries

In Python, a dictionary is a powerful data structure that allows you to store and retrieve data using key-value pairs. It is also known as an associative array or a hash map in other programming languages. Dictionaries are mutable, unordered, and can contain any type of data. They are incredibly useful when you need to store and retrieve data quickly based on a specific key.

Creating a Dictionary

To create a dictionary in Python, you use curly braces {} and separate each key-value pair with a colon :. Here's an example:

my_dict = {"name": "John", "age": 25, "city": "New York"}

In this example, we have created a dictionary called my_dict with three key-value pairs. The keys are "name", "age", and "city", and the corresponding values are "John", 25, and "New York".

Accessing Values in a Dictionary

To access the values in a dictionary, you can use the keys as the index. Here's an example:

print(my_dict["name"])  # Output: John
print(my_dict["age"])   # Output: 25
print(my_dict["city"])  # Output: New York

In this example, we are accessing the values in the my_dict dictionary using the keys "name", "age", and "city". The corresponding values are then printed to the console.

Modifying Values in a Dictionary

Dictionaries are mutable, which means you can modify the values associated with a key. To modify a value in a dictionary, you can simply assign a new value to the key. Here's an example:

my_dict["age"] = 30
print(my_dict["age"])  # Output: 30

In this example, we are modifying the value associated with the key "age" in the my_dict dictionary. We assign a new value of 30 to the key, and then we print the updated value to the console.

Adding and Removing Key-Value Pairs

You can add new key-value pairs to a dictionary by simply assigning a value to a new key. Here's an example:

my_dict["occupation"] = "Engineer"
print(my_dict)  # Output: {"name": "John", "age": 30, "city": "New York", "occupation": "Engineer"}

In this example, we are adding a new key-value pair to the my_dict dictionary. The key is "occupation" and the value is "Engineer". After adding the new key-value pair, we print the updated dictionary to the console.

To remove a key-value pair from a dictionary, you can use the del keyword followed by the key. Here's an example:

del my_dict["city"]
print(my_dict)  # Output: {"name": "John", "age": 30, "occupation": "Engineer"}

In this example, we are removing the key-value pair with the key "city" from the my_dict dictionary using the del keyword. After removing the key-value pair, we print the updated dictionary to the console.

Dictionary Methods

Python provides several built-in methods that you can use to manipulate dictionaries. Here are some commonly used methods:

  • keys(): Returns a list of all the keys in the dictionary.

  • values(): Returns a list of all the values in the dictionary.

  • items(): Returns a list of all the key-value pairs in the dictionary as tuples.

  • get(key): Returns the value associated with the specified key. If the key does not exist, it returns None by default.

  • pop(key): Removes the key-value pair with the specified key from the dictionary and returns the value.

  • clear(): Removes all the key-value pairs from the dictionary.

Here's an example that demonstrates the usage of these methods:

my_dict = {"name": "John", "age": 30, "occupation": "Engineer"}

print(my_dict.keys())    # Output: ["name", "age", "occupation"]
print(my_dict.values())  # Output: ["John", 30, "Engineer"]
print(my_dict.items())   # Output: [("name", "John"), ("age", 30), ("occupation", "Engineer")]

print(my_dict.get("name"))  # Output: John
print(my_dict.get("city"))  # Output: None

print(my_dict.pop("age"))  # Output: 30
print(my_dict)             # Output: {"name": "John", "occupation": "Engineer"}

my_dict.clear()
print(my_dict)  # Output: {}

In this example, we create a dictionary called my_dict and demonstrate the usage of various dictionary methods. We print the keys, values, and items of the dictionary, retrieve values using the get() method, remove a key-value pair using the pop() method, and finally clear the dictionary using the clear() method.

Dictionaries are a fundamental data structure in Python that allow you to efficiently store and retrieve data using key-value pairs. They are versatile and can be used in a wide range of applications. Understanding how to create, access, modify, and manipulate dictionaries will greatly enhance your ability to work with data in Python.