Hi everyone, in Python Sort Dictionary By Value tutorial, we will learn how can we sort dictionary by value. We will also learn about what is dictionary, how to create it, and many more. So let’s gets start to explore the a powerful concept of python i.e., dictionary.
All of you have heard about dictionary that helps you finding meaning of words(In any human language ) but now its time to discuss about dictionary of programming language. And dictionary is a powerful data structure in python. So in this tutorial we will see how can we deal with python dictionaries.
Python Dictionary – Meaning, Syntax and Manipulation
What is python dictionary ?
So what is a dictionary, answer is here –
- Dictionary allows us to work with key-value pair.
- Key is the unique identifier which is used to define our data and value is that data.
- Dictionaries are similar to list but dictionary stores keys and values.
- It is very useful in python and it is very dynamic data type which no other programming language contain.
- Any time we have to show relationship between two things we use dictionary.
Why We Use Dictionary ?
But the next question is that, why we use dictionary. So answer is that any time if we have relationship between two things then we use dictionary otherwise we just use List.
Let’s understand this with an example.
If you want to just remember a bunch of numbers like [1,2,4,8,7], you use list but what will you do if you have to find a phone number from your phonebook. For this you will look up a person name on your phonebook, and based on person name it will give you back their phone numbers. And this will be possible because of using the dictionary and that’s the beauty of a dictionary.
Creation Of A Dictionary
Now we will see how to create a dictionary. A dictionary is consist of a key and its value. Creation of dictionaries in python is very easy.
- You have to place the items of dictionaries inside the curly braces {} and the items are separated with comma(,).
- Item consists of a key and its corresponding value.
- Key and value is separated by colon (:).
- But one thing you have to care about is that the values can be of any data type and can be repeated but key must be unique and immutable type.
- Immutable type means it could be a string, number or tuple.
1 2 3 4 5 6 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} |
- So this is the way of creating dictionaries in python.
- Here We have taken a variable student, and the keys are Name, Roll, Age and Courses and their corresponding values are Urooz, 1234, 25 and [‘Math’ , ‘CS’] .
- Here the Name is string, Roll is integer, Age is integer and Courses is a list.
Also Read : Join Two Lists Python – Learn Joining Two Lists With Examples
Accessing Elements From A Dictionary
Now we will learn how to access elements from a dictionary.We can access the elements from dictionary using two ways –
- By using square bracket
- Using get() method
By Using Square Bracket
1 2 3 4 5 6 7 8 9 10 11 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} print(Student['Name']) print(Student['Roll']) print(Student['Age']) print(Student['Courses']) |
The output of this code is –
By Using get() method
When we access the key which is not present in dictionary then we get a error i.e., KeyError. So avoiding this error we use get() method. If the key is not found get() method returns None.
1 2 3 4 5 6 7 8 9 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} print(Student.get('Courses')) print(Student.get('phone')) |
The output is –
- Here you can see phone has None value because phone is not present in our dictionary.
Updating Elements Of A Dictionary
We can update elements of a dictionary by using two ways –
- Using assignment operator
- Using update() method
Assignment Operator
This is the code for updating dictionary using assignment operator
1 2 3 4 5 6 7 8 9 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} Student['Name'] = 'Zenelia' print(Student) |
In the output you can see now the value of Name has been changed.
Using update() method
This is usually helpful when we update multiple values simultaneously.
- update() method takes dictionary as an argument .
- And the dictionary is just everything we have to add or update.
1 2 3 4 5 6 7 8 9 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} Student.update({'Name': 'Zenifar', 'Roll':3456}) print(Student) |
So now the dictionary is like as below and the name and roll has been updated
Also Read : Recursive Function Python – Learn Python Recursion with Example
Adding Elements In The Dictionary
Now we have to add elements in the existing dictionary. For this write the following code.
1 2 3 4 5 6 7 8 9 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} Student['Phone'] = '222-555-666' print(Student) |
- You can see phone has been added into the existing dictionary.
Deleting Elements From The Dictionary
We can delete a specific key and value from dictionary by using two ways –
- del keyword
- pop() method
Using del keyword
1 2 3 4 5 6 7 8 9 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} del Student['Name'] print(Student) |
Here i am deleting Name key from Student, on running this we can see that Name key has been deleted from dictionary.
Using pop() method
pop() method removes the key but also return the value.
1 2 3 4 5 6 7 8 9 10 |
Student = {'Name': 'Urooz', 'Roll':1234, 'Age':25 , 'Courses':['Math','CS']} age = Student.pop('Age') print(Student) print(age) |
And the output is –
Also Read : Python Queue Example : Implementation, Examples and Types
Python Sort Dictionary By Value Tutorial – Getting Started With Examples
Sorting dictionary in python is not so difficult. In this section i will explain you how to sort dictionary. There are various ways to sort dictionary, so let’s see them.
First of all we have to define a dictionary. So here for example i am defining a simple dictionary that contain weight of persons.
1 2 3 4 |
Weight_details = {'Sam':45, 'Irum':67, 'Dolly':80, 'Bela':20} |
So we have to sort them by value.
Using The Sorted Function And Lambda Function
- The sorted() method sorts the elements of a given iterable in a specific order – Ascending or Descending.
Sorting in Ascending Order
Here the items will be sorted in ascending order.
1 2 3 4 5 6 7 8 9 |
Weight_details = {'Sam':45, 'Irum':67, 'Dolly':80, 'Bela':20} sorted_weight = sorted(Weight_details.items(), key=lambda x:x[1] ) print(sorted_weight) |
- sorted() method takes two argument one is the items that are to be sorted and the second is key.
- Here key is lambda which is an anonymous function. About lambda function, i have already uploaded a post so you can check it from here.
- So now you can see the dictionary has been sorted by value in ascending order.
Sorting in Descending Order
Now we will see how to sort them in descending order.
1 2 3 4 5 6 7 8 9 |
Weight_details = {'Sam':45, 'Irum':67, 'Dolly':80, 'Bela':20} sorted_weight = sorted(Weight_details.items(), key=lambda x:x[1], reverse=True ) print(sorted_weight) |
The output of this code is –
Using The Sorted Function And Operator module
- The
operator
module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example,operator.add(x, y)
is equivalent to the expressionx+y
.
1 2 3 4 5 6 7 8 9 |
import operator Weight_details = {'Sam':45, 'Irum':67, 'Dolly':80, 'Bela':20} sorted_weight = sorted(Weight_details.items(), key=operator.itemgetter(1)) print(sorted_weight) |
- itemgetter() method returns a callable object that fetches item from its operand using the operand’s _getitem_() method.
So friends this was all about Python Sort Dictionary By Value tutorial. If you have any problem regarding this then comment. And please share it as much as possible. thanks everyone.