All You Need To Know About Python Dictionaries
Dictionaries are a data type in Python that allow you to store and access data in a key-value format. They are an incredibly useful data structure, and they are a fundamental part of Python programming.
To create a dictionary in Python, you use the {}
syntax, like so:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
In this example, we have created a dictionary called my_dict that has three key-value pairs: "key1": "value1", "key2": "value2", and "key3": "value3".
The keys in a dictionary must be unique, but the values do not have to be.
To access the values in a dictionary, you use the square bracket notation and the key of the value you want to access, like so:
value1 = my_dict["key1"]
value2 = my_dict["key2"]
Output
"value1"
"value2"
You can also use the get() method to access values in a dictionary.
The get() method takes a key as an argument and returns the corresponding value, or None if the key is not found in the dictionary.
For example:
value1 = my_dict.get("key1")
value4 = my_dict.get("key4")
Output
"value1"
None
To add a new key-value pair to a dictionary, you simply assign a value to a new key, like so:
my_dict["key4"] = "value4"
To remove a key-value pair from a dictionary, you can use the del keyword, like so:
del my_dict["key4"]
You can also use the pop() method to remove a key-value pair from a dictionary.
The pop() method takes a key as an argument and removes the corresponding key-value pair from the dictionary.
It also returns the value of the removed key-value pair. For example:
value3 = my_dict.pop("key3")
print(value3)
Output
"value3"
One of the most useful features of dictionaries is that they allow you to iterate over their keys, values, or key-value pairs. To do this, you can use the keys(), values(), and items() methods, like so:
# iterate over keys
for key in my_dict.keys():
print(key)
# iterate over values
for value in my_dict.values():
print(value)
# iterate over key-value pairs
for key, value in my_dict.items():
print(key + ": " + value)
Dictionaries are a powerful and flexible data structure in Python, and they are used in a wide variety of applications.
Here are a few examples of how you might use dictionaries in your own programs:
- As a simple database to store and retrieve data.
To create a lookup table for quick access to data.
To store the results of a calculation for later use.
Reference Books
Here are the books I’ve used as references for writing this article,
please feel free to read them If you don’t want your knowledge to be
limited to this article alone.
Post a Comment