How to sort dictionary by value python

How to sort dictionary by value python

3 Ways to Sort a Dictionary by Value in Python

How to sort dictionary by value python. Смотреть фото How to sort dictionary by value python. Смотреть картинку How to sort dictionary by value python. Картинка про How to sort dictionary by value python. Фото How to sort dictionary by value python

Hey, folks! In this article, we will be unveiling the steps to sort a dictionary by value in Python.

Technique 1: Using sorted() function to sort a dictionary by value in Python

The sorted() method along with Python operator.itemgetter() method can be used to sort a dictionary by value in Python.

Python operator module has various in-built functions to manipulate the data and values. The operator.itemgetter(m) method considers the input object as an iterable and fetches all the ‘m’ values from the iterable.

Syntax: Python operator.itemgetter(m)

Python sorted() method sorts the dict in an ascending/descending order.

Syntax: Python sorted() method

Example:

In the above function, we have set the parameter key = operator.itemgetter(1) because here ‘1’ represents the values of the dict, and ‘0’ represents the keys of the dict. Thus, we have sorted the dict by values in ascending order.

Output:

Technique 2: Python lambda function along with sorted() method

Python sorted() method can be clubbed along with lambda function to sort a dictionary by value in Python in a predefined order.

Python lambda function creates an anonymous function i.e. a function without a name. It helps optimize the code.

Syntax: Python lambda function

Example:

In the above snippet of code, we have created a lambda function and passed the values of the dict as argument to it by iterating through the dict by values i.e. item[1].

Output:

Technique 3: Python sorted() method along with dict.items()

Python sorted() function can be used to sort a dictionary by value in Python by passing the values through dict.items() to the method.

The dict.items() method fetches the keys/values from a dictionary.

Syntax:

Example:

In the above snippet of code, we have passed (value,key) pair to the sorted function and have fetched the dict values using dict.items() method. In this case, we would receive the sorted (value,key) pair as the output.

Output:

Conclusion

Thus, in this article, we have understood the different ways to sort a dictionary by value in Python.

How to Sort a Dictionary by Value in Python

Introduction

A dictionary in Python is a collection of items that stores data as key-value pairs. In Python 3.7 and later versions, dictionaries are sorted by the order of item insertion. In earlier versions, they were unordered.

Let’s have a look at how we can sort a dictionary on basis of the values they contain.

Sort Dictionary Using a for Loop

We can sort a dictionary with the help of a for loop. First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary.

Note: Sorting does not allow you to re-order the dictionary in-place. We are writing the ordered pairs in a completely new, empty dictionary.

If you run this with the Python interpreter you would see:

Now that we’ve seen how to sort with loops, let’s look at a more popular alternative that uses the sorted() function.

Sort Dictionary Using the sorted() Function

Here, key is a function that’s called on each element before the values are compared for sorting. The get() method on dictionary objects returns the value of for a dictionary’s key.

The sorted(dict1, key=dict1.get) expression will return the list of keys whose values are sorted in order. From there, we can create a new, sorted dictionary:

Using the sorted() function has reduced the amount of code we had to write when using for loops. However, we can further combine the sorted() function with the itemgetter() function for a more succinct solution to sorting dictionaries by values.

Sort Dictionary Using the operator Module and itemgetter()

The operator module includes the itemgetter() function. This function returns a callable object that returns an item from an object.

For example, let’s use to itemgetter() to create a callable object that returns the value of any dictionary with a key that’s 2 :

Every dictionary has access to the items() method. This function returns the key-value pairs of a dictionary as a list of tuples. We can sort the list of tuples by using the itemgetter() function to pull the second value of the tuple i.e. the value of the keys in the dictionary.

Once it’s sorted, we can create a dictionary based on those values:

With much less effort, we have a dictionary sorted by values!

As the key argument accepts any function, we can use lambda functions to return dictionary values so they can be sorted. Let’s see how.

Sort Dictionary Using a Lambda Function

Let’s sort a dictionary by values using a lambda function in the key argument of sorted() :

Note that the methods we’ve discussed so far only work with Python 3.7 and later. Let’s see what we can do for earlier versions of Python.

Returning a New Dictionary with Sorted Values

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Here’s an example of sorting and using OrderedDict :

Conclusion

This tutorial showed how a dictionary can be sorted based on its values. We first sorted a dictionary using two for loops. We then improved our sort by using the sorted() function. We’ve also seen the itemgetter() function from the operator module can make our solution more succinct.

Lastly, we adapted our solution to work on Python versions lower than 3.7.

Variations of the sorted() function are the most popular and reliable to sort a dictionary by values.

Python Dictionary sort (11 examples)

In this Python tutorial, we will discuss Python Dictionary sort. We will see here, how to sort a dictionary in Python, how to sort dictionary in python by key and value, and the below examples:

How to sort dictionary in Python

Syntax:

Here is the Syntax of the sorted() function.

Example:

Let’s take an example to check how to sort dictionaries in Python

After writing the above code, we have to sort both values and keys available in the dictionary. In python, offers built-in functions keys() and items() to sort the dictionary. We can apply these function iterable as an argument and returns a new sorted list.

Here is the Screenshot of the following given code

This is how to sort the dictionary in Python.

Check Python dictionary sort – Another approach

Suppose we have a dictionary in Python that contains the elements on our fruit menu. So now we want to sort the ordered dictionary in descending order of values and keys. In this example, we have to use the reverse argument and assign them values as true.

Example:

Let’s take an example to check how to sort dictionary in Python by reverse method

Here is the Screenshot of the following given code

This is how to sort dictionary in Python.

Python dictionary sort by value

Example:

Let’s take an example and check how to sort a dictionary value in python in descending order.

Here is the Screenshot of the following given code

This is an example of a Python dictionary sort by value.

Python dictionary sort by value – Another example

Now we will check how to sort a dictionary by value in Python using the sorted function.

Example:

In the above code, you can check that it returns a new sorted list in ascending order.

Here is the Screenshot of the following given code

This is an example of a Python dictionary sort by value.

Python Dictionary sort by key

Example:

Let’s take an example and check how to sort a dictionary key in Python

In the above example, First, we will initialize a dictionary and assign them a key-value pair value. Then use dict.items() function to get an iterable sequence values.

Here is the Screenshot of the following given code

How to sort a dictionary keys in Python – Another approach

Using dict.keys() we can sort the dictionary keys in Python. This method returns an iterable view object that displays all the keys which is available in the dictionary.

Example:

Let’s take an example and check how to sort dictionary keys in Python

Here is the Screenshot of the following given code

This is how to sort dictionary keys in Python.

Python dictionary sort by value Descending

Example:

Let’s take an example and check how to sort a dictionary value in descending order

In the above code first, we will import an ordered dict library and create a dictionary. The key_value[1][inner_key] to sort the previous result iterable by inner key values.

Here is the Screenshot of the following given code

This is how to sort a Python dictionary by value Descending.

Python dictionary sort by value alphabetically

Example:

Let’s take an example and check how to sort dictionary values alphabetically.

Here is the Screenshot of the following given code

Python dictionary sort by key alphabetically

Example:

Here is the Screenshot of the following given code

This is how to sort a Python dictionary by key alphabetically.

Python dictionary sort reverse

Example:

Let’s take an example and check how to reverse the order of keys

Here is the Screenshot of the following given code

This is an example of a Python dictionary sort reverse.

How to reverse the order of keys in Python dictionary

In this example, we will use the combination of dictionary functions to perform this particular task. By using list(),keys(),sorted(),reversed(). It will sort the keys and reversed gets the key extracted using dict.keys() function in descending order.

Example:

Here is the Screenshot of the following given code

This is how to reverse the order of keys in a Python dictionary.

Python dictionary sort by key value

Example:

Let’s take an example and check how to sort key-value pairs in the dictionary.

Here is the Screenshot of the following given code

This is how to sort a python dictionary by key value.

Python dictionary sort with lambda

Example:

Let’s take an example and check how to sort a dictionary with a lambda function

Note: For descending order use “reverse=True”

In the above example, we are using sorted() with a lambda function. First, initialize the list of dictionaries and using the sorted and lambda function to print the list sorted by the “Val” attribute. Using sorted and lambda function to print list sorted by “Val” in descending order.

Here is the Screenshot of the following given code

This is how to sort a Python dictionary with lambda.

Python dictionary sort by alphabetically

Example:

Let’s take an example and check how to sort a dictionary alphabetically

Here is the Screenshot of the following given code

This is how to sort a python dictionary alphabetically.

Python dictionary sort by value list

Example:

Here is the Screenshot of the following given code

This is how to sort value in the list in Python.

Python sort dictionary by value then key

Example:

Let’s take an example and check how to sort a dictionary by value than the key

Here is the Screenshot of the following given code

This is how to sort a dictionary by value then key in Python.

You may like the following Python tutorials:

In this Python tutorial, we will discuss Python Dictionary sort. Here we will also see the Python create string examples:

How to sort dictionary by value python. Смотреть фото How to sort dictionary by value python. Смотреть картинку How to sort dictionary by value python. Картинка про How to sort dictionary by value python. Фото How to sort dictionary by value python

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

In this article we will discuss how to sort the contents of dictionary by key or value.

Suppose we have a dictionary of string and ints i.e.

Dictionary is like a hash table that store the elements by calculating hashes of keys and orders of elements in it can not be predicted. Therefore, its also called unordered container and we can sort the dictionary in place. But we can create a either create a list of tuples (key value) pairs which is sorted or we can iterate over the contents of dictionary in sorted order.

Let’s see how to do sort the contents of dictionary in different ways,

Sort a dictionary contents by key

There are different ways to sort the elements of dictionary be keys i.e.

Sort Dictionary contents by keys using dict.keys()

It returns a iterable view of all the keys in dictionary.

We can create a new sorted dictionary from this iterable sequence of keys i.e.

Now we will iterate over this sorted list of keys and select each entry from dictionary i.e.

It will print the dictionary in a sorted order of keys i.e.

Now we can achieve the same thing using an another function of dictionary i.e. items(). Its more efficient.

Sort Dictionary contents by keys using dict.items()

It returns an iterable sequence of tuples that contains all key value pairs in dictionary.
We can create a new sorted list of tuple by this iterable sequence i.e.

By default sorted will sort the list of tuple by 1st element in tuple i.e. on 0th index. So list of tuples (key / value pairs) is sorted by keys. Now we can iterate over this sort list of tuple i.e. all sorted keys value pairs from dictionary i.e.

It will print the dictionary in a sorted order of keys i.e.

It’s more efficient than previous method in terms of complexity, because after sorting the iterable sequence we don’t need to search for value for key like in case of dict.keys().

We can achieve the same using List Comprehension i.e.

Sorting dictionary contents in reverse order of keys

Both the previous solutions sorted the dictionary by key but in ascending order. What if we want to sort the contents by descending order of keys. We can so this by simply passing an attribute in sorted() function i.e. reverse=True i.e.

Let’s use this to sort the list of tuples by keys (0th index element) and in reverse order i.e. descending order,

It will print the dictionary in a sorted order of keys in reverse i.e.

Sort dictionary contents by key using custom key functions

We can also sort the contents of dictionary by custom logic. Like in case our dictionary we want to sort by the length of key strings.

sorted() function accepts a key function as an argument and calls it on each element prior to make comparison with other elements.
So, to sort the dictionary keys by length of string, we will pass a lambda function as key function that will return the size of string i.e.

It will create a list of tuples, sorted by key size i.e.

Sort dictionary contents by Value

To sort dictionary elements by value we will use the same sorted() function and pass a key function that will return the 1th index element of tuple i.e. the value field from the key/value pair,

As this key function will be called on each element before making comparison while sorting, so the list of tuples will be sorted by value i.e.

We can do the same using List comprehension too,

Sorting dictionary by value in reverse Order

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows,

Output:

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

How do I sort a list of dictionaries by a value of the dictionary?

How do I sort a list of dictionaries by a specific key’s value? Given:

19 Answers 19

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

The sorted() function takes a key= parameter

Alternatively, you can use operator.itemgetter instead of defining the function yourself

For completeness, add reverse=True to sort in descending order

How to sort dictionary by value python. Смотреть фото How to sort dictionary by value python. Смотреть картинку How to sort dictionary by value python. Картинка про How to sort dictionary by value python. Фото How to sort dictionary by value python

To sort the list of dictionaries by key=’name’:

To sort the list of dictionaries by key=’age’:

my_list will now be what you want.

Since Python 2.4, there’s a key argument is both more efficient and neater:

If you want to sort the list by multiple keys, you can do the following:

It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).

‘key’ is used to sort by an arbitrary value and ‘itemgetter’ sets that value to each item’s ‘name’ attribute.

I guess you’ve meant:

This would be sorted like this:

You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That’s usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.

You could do it this way:

More on the Perl Schwartzian transform:

In computer science, the Schwartzian transform is a Perl programming idiom used to improve the efficiency of sorting a list of items. This idiom is appropriate for comparison-based sorting when the ordering is actually based on the ordering of a certain property (the key) of the elements, where computing that property is an intensive operation that should be performed a minimal number of times. The Schwartzian Transform is notable in that it does not use named temporary arrays.

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

Using the Pandas package is another method, though its runtime at large scale is much slower than the more traditional methods proposed by others:

Here are some benchmark values for a tiny list and a large (100k+) list of dicts:

The list to be sorted:

Sorting it in-place:

Let’s say I have a dictionary D with the elements below. To sort, just use the key argument in sorted to pass a custom function as below:

I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.

First option

Second option

Fast comparison of execution times

1000000 loops, best of 3: 0.736 µsec per loop

1000000 loops, best of 3: 0.438 µsec per loop

If performance is a concern, I would use operator.itemgetter instead of lambda as built-in functions perform faster than hand-crafted functions. The itemgetter function seems to perform approximately 20% faster than lambda based on my testing.

Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).

Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *