❓What is a dictionary❓
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.
Retrieving data from a dictionary 📖
Square brackets are used to get the value of a particular key []
. Suppose we have a pair in our dictionary 'marathon': 26
.
Again, you will get an error if you try to retrieve a value for a non-existent key. There are methods to avoid such mistakes, which we will talk about now.
Adding and updating keys 🔑
Adding new pairs to the dictionary is quite simple:
Updating existing values is exactly the same:
Deleting keys ❌
To remove a key and corresponding value from a dictionary one can use del
🍴 Methods 🍴
Python dictionaries have many different useful methods to help you in your work with them. Here are just a few of them.
👉 Update
The method 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.
👉 Get
Let's suppose we have a dictionary:
The method get()
returns the value for the specified key. If the specified key does not exist, the method will return None
.
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
The method pop()
deletes the key and returns the corresponding value.
👉 Keys
The method keys()
returns a collection of keys in the dictionary.
👉 Values
The method values()
returns the collection of values in the dictionary.
👉 Items
The method items()
returns key-value pairs.
👉 Iterating through a dictionary
You can iterate over each key in the dictionary.
Obviously, instead of story_count
you can usestory_count.keys()
.
In the example code below, the loop for
uses the methoditems()
to get a key-value pair for each iteration.
Read More
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.
Top comments (1)
I think you are great! i just want to discuss tech with Python developer.
I built a display machine state using Python3 with Flask!
Flask State Github:github.com/yoobool/flask-state
Should i can get some improvement suggestions from you? Thanks~