Python dictionaries are a versatile and widely used data structure that allows you to store key-value pairs. They are mutable, unordered collections, meaning the elements are stored and accessed by their keys rather than their position. Here's an overview of Python dictionaries:
You can create a dictionary by enclosing key-value pairs within curly braces `{}`, separated by commas and with colons `:` separating keys and values.
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
Alternatively, you can use the `dict()` constructor and pass it key-value pairs as arguments.
my_dict = dict(key1="value1", key2="value2", key3="value3")
You can access the value associated with a key by using square brackets `[]` and providing the key.
print(my_dict["key1"]) # Output: value1
You can add new key-value pairs or modify existing ones by assigning a value to a new key or an existing key, respectively.
my_dict["key4"] = "value4" # Adding a new key-value pair
my_dict["key2"] = "new_value" # Modifying an existing value
Python dictionaries come with a variety of built-in methods for performing operations such as adding, removing, or accessing elements, as well as retrieving keys and values.
You can iterate over dictionaries using a `for` loop to access keys, values, or key-value pairs.
Iterating over keys
for key in my_dict:
print(key)
Iterating over values
for value in my_dict.values():
print(value)
Iterating over key-value pairs
for key, value in my_dict.items():
print(key, value)
You can check if a key exists in a dictionary using the `in` and `not in` operators.
if "key1" in my_dict:
print("Key 'key1' exists in the dictionary")
Similar to list comprehensions, you can also use dictionary comprehensions to create dictionaries in a more concise manner.
my_dict = {key: key**2 for key in range(5)}
print(my_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Python dictionaries are incredibly useful for storing and accessing data in a flexible manner.