A dictionary is an unordered data structure that allows you to store key-value pairs. Here's an example of a Python Dictionary:
This dictionary uses strings as keys, but the key can be, in principle, any immutable data type. The value of a particular key can be anything. Here's another example of a dictionary where keys are numbers and values are strings:
An important clarification: if you try to use a mutable data type as a key, you will get an error:
In fact, the problem is not with mutable data types, but with non-hashable data types, but usually, they are the same thing.
Square brackets are used to get the value of a particular key
. Suppose we have a pair in our dictionary
Adding new pairs to the dictionary is quite simple:
Updating existing values is exactly the same:
To remove a key and corresponding value from a dictionary one can use
Python dictionaries have many different useful methods to help you in your work with them. Here are just a few of them.
update() is useful if you need to update several pairs at once. The method takes another dictionary as an argument.
If you are wondering why the data in the dictionary is not in the order in which it was entered, it is because the dictionaries are not ordered.
Let's suppose we have a dictionary:
get() returns the value for the specified key. If the specified key does not exist, the method will return
The method can be used to check for the presence of keys in the dictionary:
You can also specify a default value that will be returned instead of
None if the key is not in the dictionary:
pop() deletes the key and returns the corresponding value.
keys() returns a collection of keys in the dictionary.
values() returns the collection of values in the dictionary.
items() returns key-value pairs.
You can iterate over each key in the dictionary.
Obviously, instead of
story_count you can use
In the example code below, the loop
for uses the method
items() to get a key-value pair for each iteration.
If you found this article helpful, click the💚 or 👏 button below or share the article on Facebook so your friends can benefit from it too.