Python dictionaries are a fundamental data structure that can be thought of as a fancy address book or a collection of labeled containers. They are used to store and manage collections of data, but unlike lists, which use numerical indexes to access elements, dictionaries use labels, called "keys," to organize and retrieve their data.
Basic Structure
You can create a dictionary by enclosing key-value pairs in curly braces {}
. Keys and values are separated by colons, and individual key-value pairs are separated by commas.
In the above example:
"key1"
,"key2"
, and"key3"
are keys."value1"
,"value2"
, and"value3"
are their corresponding values.
Thus, the code produces the below result.
Accessing Keys
You can access values in a dictionary by using their corresponding keys. For example:
The above code will give output the below result.
This is like looking up a phone number in an address book using the person's name.
Modifying Values
You can change the value associated with a key:
Run the program and you will the below output.
Adding New Entries
You can add new key-value pairs to a dictionary:
Once you run the program, you will get the below result:
Removing The Entries
You can delete existing key values and their pairs in a dictionary.
This line of code uses the del
statement to remove the key "key3"
and its associated value from the my_dict
dictionary. After deleting "key3"
, printing my_dict will show the updated dictionary with "key3"
removed. The output will be:
Checking if a key exists
You can check if a certain key exists in a dictionary
In this code:
You specify the key for which you want to retrieve the values by setting the
key_to_retrieve
variable to the desired key.You use an
if
statement to check if the specified key exists in the dictionary (key_to_retrieve in my_dict
).If the key exists in the dictionary, you access the values associated with that key by using
my_dict[key_to_retrieve]
.You print the values to the console. In this example, we're using an f-string to create a formatted output.
If the key is not found in the dictionary, it will print a message indicating that the key does not exist. Since "key1" exists, the program prints the below output:
Concluding our discussion for today, our next article will delve into more advanced aspects of Python dictionaries.