How To Sort A Dictionary By Value In Python?

How To Sort A Dictionary By Value In Python?

Python is an advanced-level interpreted programming language that belongs to the category of being easy to read, learn and comprehend. As it is a general-purpose programming language, the usage of Python has no typical boundaries. Let’s know How To Sort A Dictionary By Value In Python?

It can be utilized for various purposes ranging from Artificial Intelligence, Web Development, App development, Machine Learning, and several others. Its ‘object oriented’ pattern has been appreciated and Python 2.0 is certainly dear to the IT industry. 

Python is the successor of the ABC programming language and is a fascinating ponder because of its spreading roots in almost all the spheres of the tech field. 

What is a Dictionary in Python?

Similar to a thesaurus curation or an actual dictionary, the Python Dictionary is also an orderly collection of data values, stores those data values, and can hold more than a single element or values, if the assigning process with the key-value is executed well. 

However, a dictionary generally has the mapping procedure of one-to-one mapping. The one to many procedures can be adopted in the key of the dictionary by opting for duplication approaches in the values of sets of the keys. 

Dictionary in Python can be subjected to further edits and changes even after it is declared as a dictionary; it is therefore mutable. Dictionaries in Python can be easily created by placing curly brackets. It allows duplications of only values while the keys stay distinct, meaning they are immutable. And, those values can be accessed by forming an index. 

How to Create A Dictionary in Python?

Dictionary creation in Python is not rocket science. Only place the designated item in the curly bracket and separate it with colon and comma. The item consists of a key, an immutable distinct component, and a value. The pair can be represented as key: value. 

Another function that has to be used to create a dictionary is the in-built dict() function. 

For example: dict1 = {“Name”: “Natasha”, “Age”: 40, “Billno”: 0221 }

Here, ‘Name’, ‘Age,’ and ‘Billno’ are represented as keys that are unique while ‘Natasha,’ ‘40,’ and ‘0221’ are the values that can be duplicated and entered many times. The dict1 represents the first entry in the dictionary or you can say the name of the data used in the curly bracket. 

This is the first and foremost basic step to create a dictionary. The more one delves into the creation of a dictionary, the more items it can occupy. You can also create a nested dictionary. It means that a dictionary will be holding the coding of another dictionary in itself. 

For receiving the final output after the desired dictionary has been created, use the print function. Type, print(dict) and done. The output of the dictionary will be shown right away. The enclosed bracket of the print function consists of the name of the dictionary that has been made. 

Dictionaries are Mutable!

As dictionaries are mutable in Python, they can be altered. It means, the elements can be added and subtracted in a dictionary. But how?

Accessing an Element 

Any element in a dictionary can be accessed by using certain arguments and functions, based on the key value. Mostly, the ‘Get’ function is used to access an element in the dictionary. It is represented as get(). The key can be paired with the get() method or it can be indulged with the square bracket. 

For example: Given here is the personal detail of a student. 

student = {‘name’: ‘Rose’, ‘age’: 12}

Input:-

# Output: Rose

print(student[‘name’])

(Note: Here the square bracket function is being used. The square bracket has been used on the key ‘name.’ Therefore, the value associated with the key, which is Rose, will pop up when the output of the command is printed)

# Output: 12

print(student.get(‘age’))

(Note: Here, the get() function is being used to access a value via its key. The get() encloses the age of the student. Therefore, the output associated with the age as the key is 12 that will be printed when the coding proceeds)

# Output

print(student.get(‘gender’))

# KeyError

print(student[‘gender’])

(Note: If watched carefully, any key named ‘gender’ does not exist. Therefore, trying to access a value via its key which does not exist will show an error in the output when printed)

Output:-

Rose

12

None

KeyError: ‘gender’

But, if a key is not found then the message printed will be ‘None’ while deploying the get() function. It will be ‘Key Error’ shown if a key is unavailable while using the square brackets. 

You can also use the list() function to access an element of the dictionary in python. 

Adding an Element

One can also update the list by adding an element in the dictionary. It does not have any specific function; only the same dict() function and a hashtag of ‘update in the existing dictionary’ is enough to get the item added to the dictionary. 

For example: The dictionary provided here is a student detail. 

student_dict = {‘name’: ‘Rose’, ‘age’: 12}

Input:-

# update the value

student_dict[‘name’] = Liam

#Output

{‘age’: 12, ‘name’: ‘Liam’}

print(name_dict)

(Note: There is an update shown here. It is not necessary to add this step while adding a value in an element. It can be happily skipped while adding an element. This method of updating is needed only when you need to change a key value. Here, the value that was changed is the name of the person from Rose to Liam)

# add item

name_dict[‘address’] = ‘California’

# Output: {‘address’: ‘California’, ‘age’: 12, ‘name’: ‘Liam’}

print(student_dict)

Output:-

{‘name’: ‘Liam’, ‘age’: 12}

{‘name’: ‘Liam’, ‘age’: 12, ‘address’: ‘California’}

It can be seen that the address was previously not there in the present. However, it got added now. 

Deleting or Subtracting an Element

The dictionary can also be altered by deleting an element from the dictionary. It is an easy process of pop() function in the key-value. When you deploy pop item(), the arbitrary items that are the key-value pair will be removed as per command. However, there is also a clear() function command that will entirely erase the items. 

Plus, there exists a del keyword that can perform the removal function and even erase all the items present in the dictionary. 

For example: Given here is a dictionary with numerical values. An item has to be removed. 

# Removing elements from a dictionary

# create a dictionary

numbers = {11: 121, 12: 144, 13:169, 14: 196, 15: 225}

# removes an arbitrary item

# Output: (15, 225)

print(squares.popitem())

(Note: The item that has been commanded to be removed is (15, 225). The output printed accordingly will show this key-value pair erased. This is the method to remove a particular item from a dictionary)

# Output: {11: 121, 12: 144, 13: 169, 14: 196}

print(numbers)

# remove all the items

numbers.clear()

(Note: This coding is used to entirely erase the key-value pairs that are present in the data. When the output of this command gets printed, there will be empty curly brackets because the clear() function has wiped out the rest of the items)

# Output: {}

print(numbers)

# delete the whole dictionary

del number

# Throws Error

print(numbers)

(Note: The del keyword will now remove the entire function. The name of the dictionary will not exist anymore. Therefore, an error message will pop up when the print() is deployed for ‘numbers’ dictionary)

Output

{11: 121, 12: 144, 13: 169, 14: 196}

{}

NameError: name ‘numbers’ is not defined

How to sort a dictionary in python?

A dictionary in Python is sorted by a sorting function. The sorting function to be used is represented by sorted(). It can be used in various ways to sort, like by value or by keys. 

There is also a method to sort the dictionary by list comprehension technique. 

But, what is this sorted() function? 

The ‘sorted’ function is a python function that is used to give a segregated output as per the desirable command entered. It is used to sort iterable items including lists, tuples and dictionaries by value and key. 

The syntax for the sorted() function is given as the following representation: 

sorted(item/object, key, reverse)

The item/object belongs to the category of iterable object that essentially requires sorting via the ‘sorted’ function. While the key represents the distinctive component, the reverse function is used to define how the object will be sorted. It means that when the reverse function is used, the sorted data will be segregated as output in descending order. 

The only specification required for sorting is mainly the mentioning of an iterable object that has to be sorted out. The rest, like the key and reverse function of the part, is optional. Using these would make the segregation process a customized sorting procedure. 

Interestingly, when the reverse command is not mentioned or when neither the key nor the reverse command is mentioned, the function automatically sorts itself in ascending order. Sorting the data in ascending order is, therefore, the by default setting of the Python in-built sorting function. 

The optional parts, key and reverse functions, along with the iterable object intended for sorting are enclosed in the bracket of the sorted() function. They are then separated by commas.

For example: Consider a data of misarranged numbers, or alphabets. They are neither in ascending or in descending order. 

data = (8, 12, 9, 0, 6) 

Input: data.sort()

print(data)

Output: (0, 6, 8, 9, 12)

As per the output received, the conclusion can be drawn that the absence of a key or/and reverse function has resulted in the by default sorting of the data. The data gets sorted in ascending order. Also, the print(data) is the command given in python that has been entered to bring out the output based on the sorting() function performed before. 

For the output to be printed in reverse or descending format, the reverse function has to be set True. When we either do not enter the reverse function or set the reverse function on False, the output turns out to be in ascending order. It is noted that the default setting of not using the reverse function automatically implies reverse set on False and therefore the ascending order output. 

To demonstrate ascending order:- 

For example, there is data that shows the names of the pupils. 

pupils = (‘Alexa,’ ‘Sandra,’ ‘Beatrix,’ ‘Charlotte’)

Input: pupils.sort(reverse = False)

print(pupils)

Output: (‘Alexa,’ ‘Beatrix,’ ‘Charlotte,’ ‘Sandra’)

The output printed is similar to the one that had been printed when the reverse function was not mentioned. Therefore, it proves the ascension of ascending order both in the absence of reverse and the presence of reverse in False settings. 

To demonstrate descending order:-

For example, there is data that shows the names of the pupils. 

pupils = (‘Alexa,’ ‘Sandra,’ ‘Beatrix,’ ‘Charlotte’)

Input: pupils.sort(reverse = True)

print(pupils)

Output: (‘Sandra,’ ‘Charlotte,’ ‘Beatrix,’ ‘Alexa’)

When the input was given as reverse set to True, we received a reverse or descending order output in the end. 

Using Lists To Sort

The list comprehension method involves using lists so that the complexity of the sorting tactics can be avoided, especially if it is nested as conjugated nested ones take time to sort if sorting functions are allocated. 

Therefore, create a list for the list comprehension method. 

For example, The players from some countries perform in a game and the following is a score obtained by each. We have to sort the following now. 

countries = {‘Ireland’: 7, ‘India’: 6, ‘USA’: 11, ‘Australia’: 1, ‘Pakistan’: 9}

Input:-

[print(key, value) for (key, value) in sorted(countries.items(), key=lambda x: x[1])]

Output:-

(‘Australia’: 1, ‘India’: 6, ‘Ireland’: 7, ‘Pakistan’: 9, ‘USA’: 11)

Therefore, the list comprehension method sorted the entire coding and such results will be obtained again if the sorted() function was used instead of it. 

Sorting by Operator Itemgetter

Up till now, there have been two methods of sorting. The third method is using the operator item getter. To be specific and accurate, here is some coding to enable the proper implementation of the sorting process by using an example. 

Example: lis = [{ “name” : “Amisha”, “age” : 12}, 

{ “name” : “Manny”, “age” : 15 },

{ “name” : “Natasha” , “age” : 18 }]

Input:- 

print sorted(student, key=itemgetter (‘age’))

(Note: This coding will print the output based on the age of the students listed in ascending order)

print sorted(student, key=itemgetter (‘age’ , ‘name’)

(Note: This coding will print the output based on the age as well as name in alphabetically ascending order)

Output:- 

[{ “name” : “Amisha”, “age” : 12}, 

{ “name” : “Manny”, “age” : 15 },

{ “name” : “Natasha” , “age” : 18 }]

[{ “name” : “Amisha”, “age” : 12}, 

{ “name” : “Manny”, “age” : 15 },

{ “name” : “Natasha” , “age” : 18 }]

The ‘operator itemgetter’ function, represented as operator. item getter is generally used instead of the lambda function to attain the same sorting function via the key-value. Its implementation differs from that of both because it carries the keys and transforms them into tuples so that the coding could be performed swiftly. The output can now be delivered precisely in a concise and efficient form. 

Conclusion

A dictionary can be made by the usage of keys and values under it. There are also many keyword functions, parameters, and arguments. The plethora of subjects present in the dictionary glossary also has a certain importance to various brackets. 

A dictionary also has some other in-built functions like any(), all(), len() and cmp(). The len() function is an interesting one; it sorts the dictionary with regards to the length of characters or letters used. Only put print sorted(dict, key=len()).

The sorted() function is also an in-built function of the dictionary. Out of the many processes, sorting is the most common procedure that has been undertaken several times in python and is also not a rare need. Some of the other processes and procedures that can be tested in the dictionary are iterating and membership tests. 

Frequently Asked Questions

1) Why do the keys stay distinct in a python while the values can be duplicated? 

The keys have to stay distinct because if duplication of keys is done then there will be overwriting over the values assigned priorly to the key. That is why keys can range from being integers, strings, and tuples but they cannot be lists. 

It is so because lists are mutable, meaning they can be altered while Keys are immutable, meaning keys cannot be toyed with. 

2) What is the lambda function in Python?

It is a no-name function that has only one expression but many arguments to deliver. Sometimes, this function is even given away as an argument while performing functions. Lambda function, represented as ‘lambda,’ is known as an anonymous function that can behave as regular functions. It is needed when the function has to be performed in a short period and can take some other functions into account with itself too, like filter() function, and map() function. 

3) What are the arguments?

In simple words, an argument is a value that gets assigned to a function when it gets to perform. This acts as an information agent; when a function has to be performed, the value or information gets transferred to it via the name of an argument. An argument in a function is supposed to be accurate and precise, it is not something to be played around with. If a function asks for a certain number of arguments, the output printed should be with the same number of arguments. Arguments can be coined into ‘args.’

4) What are tuples and lists?

Lists and tuples are sequential data types that can store any kind of data in it which can be accessed by their indexes. However, lists are mutable while tuples are immutable. Lists store multiple data in square brackets whereas tuples store the data in parentheses. They both are components of python, with nearly similar functions. 

How To Sort A Dictionary By Value In Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top