In this article, we’ll learn what Python dictionary is and how to properly define and use it in code.
We’ll be going through multiple practical code examples with step by step explanation to better understand how Python dictionary works.
After reading this post, you’ll have a thorough understanding of how to easily use Python dictionary.
So without any delay, let’s just dive right into its practical implementation.
What is Python Dictionary?
Dictionary in Python consist of a key value pairs. The data of value can be fetched using its specified key. It’s an unordered list of items. Python dictionary can hold values of different datatype.
Let’s first understand the syntax of Python dictionary. After that, we’ll go through multiple practical examples to understand how to set and fetch data from it.
Syntax of Python Dictionary
dictionaryName = {key:value, key:value, key:value}
Explanation
The body of dictionary is specified using the curly braces ( {} ).
Then comes the key value pairs. A colon ( : ) is used to separate the key and value. Key can be of any datatype like string, int etc. Value can also be of different datatypes.
Let’s now understand its practical implementation.
Implementing Python Dictionary (Multiple Examples)
Below examples will practically demonstrate how to use Python dictionaries.
Example 1: Create a Dictionary
dicItems={'name':'Zeeshan', 'age':24, 2:'green', 4.5:34}
As you can see that we’ve used keys of multiple datatype and also we have specified the assigned values having different datatypes. You can specify all keys with same datatype like string, int etc.
Example 2: Fetch Data from Dictionary
We can use 2 methods to access data from Python dictionary.
- Using square brackets []
- Using get() method
Using Square brackets [] To Fetch Data From Dictionary
Let’s fetch data from then above mentioned Python dictionary.
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems['name']) // name is a key print(dicItems['age']) // age is a key print(dicItems[2]) // 2 is a key as defined in above dictionary print(dicItems[4.5]) // 4.5 is also a key
Output
Zeeshan 24 green 34
Using get() Method To Fetch Data From Dictionary
Let’s now fetch data using get() method.
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems.get('name')) print(dicItems.get('age')) print(dicItems.get(2)) print(dicItems.get(4.5))
Output
Zeeshan 24 green 34
We can see that both these methods show same results.
So what’s the difference between them?
If we use the bracket method to find value of a specific key but that key is not present in dictionary. Then it’ll give an error while if we use the get() method in same situation then it’ll just return none. See below code example:
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems['id']) // KeyError: 'id' print(dicItems.get('id')) // None
Example 3: Update the Values and Items in Dictionary
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34}
print(dicItems) // {'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34}
dicItems['age']=22
dicItems['name']='Yasir'
dicItems[2]='Blue' //updates the current item
dicItems[4.5]=3838
dicItems['height']=6 // new item added to dictionary
print(dicItems) // {'name': 'Yasir', 'age': 22, 2: 'Blue', 4.5: 3838, 'height': 6}
Output
{'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34} // old dictionary {'name': 'Yasir', 'age': 22, 2: 'Blue', 4.5: 3838, 'height': 6} //updated dictionary
This is how you can update the items of dictionary using the keys specified to them. We also have added a new item in the dictionary as mentioned in the above code. New item will be added after the last item(key value pair) of dictionary.
Example 4: Remove Items from Dictionary
We can use the below methods to remove items from dictionary, clear the whole dictionary or even delete dictionary. See below examples:
Using pop() Method
Its used to specify which key value pair should be deleted. We just have to pass a specific key to this method. See below code:
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems) // {'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34} print(dicItems.pop('age')) // remove the key value pair having a key name 'age' and return it print(dicItems) // {'name': 'Zeeshan', 2: 'green', 4.5: 34}
Output
{'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34} // old dictionary 24 // popped item's value {'name': 'Zeeshan', 2: 'green', 4.5: 34} // updated dictionary
Using popitem() Method
It is used to remove the last item( key value pair) of dictionary. See below code:
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems) print(dicItems.popitem()) // remove last item(key value pair) of dictionary print(dicItems)
Output
{'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34} (4.5, 34) // last item(key and value) of dictionary which is now removed {'name': 'Zeeshan', 'age': 24, 2: 'green'}
Using clear() Method
It is used to clear/remove all the items from the dictionary. See below code:
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems) print(dicItems.clear()) // remove all items from dictionary print(dicItems)
Output
{'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34} None {} // all items removed
Using del Keyword
It is used to remove/delete the whole dictionary. See below code:
dicItems={'name':'Zeeshan','age':24,2:'green',4.5:34} print(dicItems) del dicItems //delete the whole dictionary print(dicItems)
Output
{'name': 'Zeeshan', 'age': 24, 2: 'green', 4.5: 34} NameError: name 'dicItems' is not defined // dictionary is deleted
So this is how you can easily define, fetch, update and remove elements/data from Python dictionary. Hope you like this post. You can try passing lists, tuples or sets to the elements of Python dictionary or creating dictionary using dict() method and share your experience with us.
Feel free to ask if you still have any questions regarding the implementation of Python dictionary. I’ll be very happy to answer all your questions.
Conclusion
To conclude this post, hope you now have a detailed practical understanding of how to define and use Python dictionary. I’d be delighted to receive your valuable thoughts on this post. Thank you for reading it.