Python Dictionary
In Python, a dictionary is an unordered collection of key-value pairs. Dictionaries are a useful data type when you need to store a collection of items that can be accessed using a unique key.
Here's an example of how to create a dictionary in Python:
my_dict = {"apple": 1, "banana": 2, "orange": 3}
In this example, we've created a dictionary with three key-value pairs. The keys are strings that represent the names of fruits, and the values are integers that represent the quantities of each fruit.
You can access the values in a dictionary using the keys:
print(my_dict["apple"]) # prints 1 print(my_dict["banana"]) # prints 2
You can also modify the values in a dictionary:
my_dict["apple"] = 4
This changes the value associated with the "apple" key to 4.
You can add new key-value pairs to a dictionary:
my_dict["pear"] = 5
This adds a new key-value pair to the dictionary with the key "pear" and the value 5.
You can remove key-value pairs from a dictionary using the del
keyword:
del my_dict["orange"]
This removes the key-value pair with the key "orange" from the dictionary.
Dictionaries are a useful data type when you need to store a collection of items that can be accessed using a unique key. They are commonly used in many areas of programming, such as database applications and web development.