In Python, a dictionary is another commonly used data structure that allows you to store and manipulate collections of data. A dictionary is an unordered collection of key-value pairs, where each key must be unique and immutable, and each value can be of any data type.
Here is an example of creating and working with a dictionary in Python:
python # Create a dictionary my_dict = {"name": "Alice", "age": 30, "city": "New York"} # Access values in the dictionary print(my_dict["name"]) # Output: "Alice" print(my_dict["age"]) # Output: 30 # Add a new key-value pair to the dictionary my_dict["job"] = "Engineer" # Iterate over the keys and values in the dictionary for key, value in my_dict.items(): print(key + ": " + str(value))
In this example, a dictionary called `my_dict` is created with three key-value pairs. The `print()` function is used to access and output the values associated with the `”name”` and `”age”` keys. The `my_dict[“job”] = “Engineer”` line adds a new key-value pair to the dictionary. Finally, a `for` loop is used to iterate over the keys and values in the dictionary and output them to the console.
Dictionaries in Python can also be used to represent complex data structures, such as nested dictionaries. Here is an example:
python # Create a nested dictionary my_dict = {"person1": {"name": "Alice", "age": 30}, "person2": {"name": "Bob", "age": 25}} # Access values in the nested dictionary print(my_dict["person1"]["name"]) # Output: "Alice" print(my_dict["person2"]["age"]) # Output: 25
In this example, a nested dictionary called `my_dict` is created with two key-value pairs, where each value is another dictionary. The `print()` function is used to access and output the values associated with the `”name”` key in the `”person1″` dictionary and the `”age”` key in the `”person2″` dictionary.
Dictionaries are a powerful data structure in Python and are useful for a wide variety of applications, such as representing data in a database or organizing data for analysis.