In Python programming, there are different data types that stores data collections. Python dictionary is one of these methods. The others are python lists, python tuples and python sets. Here, with different dictionary coding exmaples, we will learn the detals of this data type.
In dictionaries, there are “key:value” pairs. These key:value pairs are written between curly brackets {}.
Other Dictionary Lessons:
Dictionaries are ordered data types and they can be changed. And duplicate items do not allowed in a python dictionary.
Below, let’s give an example for dictionaries.
The output of this python code will be:
You can also watch the video of this lesson!
Python dictionaries are defined as objects that has “dict” daha type.
You can practice below!
There are different functions used with python dictionaries. One of them is len function. We can find the length of a dictionary with this fucntion.
The output of this ode will be:
Table of Contents
We have showed python dictionary examples above. So, how can we create them. There are differetn methods to create a python dictionary. Let’s see each of them with an example.
The first example is created with only curly brackets like below. The key:value pairs are defined between these curly brackets.
The second method to create a dictionary is using dict method.
The last creation method is dict method again. Here, we define each pair between round pharanthesis and a comma between key and value.
For various reaons, we access the items of a list, a tuple or a dictionary. So, how can we do this with dictionaries. We can use the name of the key inside square brackets to access a specific dictionary value.
Below, we will access name key.
The output of this code will be:
Now, let’s use access method to access a device model:
The output will be:
Instead of this method, we can also use get method to access any item in a python dictionary. Here, the difference is using round pharanthesis instead of square pharantesis. And the get keyword for get method.
We can change the items of a python dictionary. We can do this by adding a new key:value pair or by changing an existing key:value pair.
In the below example, we will add a new key:value pair to our dictionary.
Now, let’s change an existing value of a key:value pair.
We can also do this with the help of python update method.
The output of this code will be:
In this lesson, we have talk about python dictionaries. We have learned how to create a python dictionary, how to access the items of this dictionary. We have also learned changing any key:value pair with different examples. You can increase examples on this lessons. In the following lessons, we will learn the details of python dcitionaries with more coding examples.
Leave a Reply