How do I sort a dictionary by value?
Python 3.7+ or CPython 3.6
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
or
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Older Python
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x
will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x
.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed we can use
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use collections.OrderedDict
:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
How do you sort a dictionary by value?
Use:
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
How do I sort a list of dictionaries by a value of the dictionary?
The sorted()
function takes a key=
parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter
instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True
to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
Sort Dict by Values in Python 3.6+
By default, the dictionary is sorted based on keys, but the sorted function takes a function as a parameter using which you can alter the behaviour for
program.
d={'a':6,'b':4,'k':3}
print(sorted(d))
sorted_by_values= sorted(d,key=lambda x:d[x])
print(sorted_by_values)
Python sort dictionary based on value inside a list
>>> dict(sorted(x.items(), key=lambda item: item[1][0]))
out:
{'Beat': [18, '100% to work', '10%'], 'Nikolas': [25, '29% to work', '94%'], 'George': [68, '0% to work', '70%']}
How to sort dictionary based on values and if multiple keys have same values then sort by keys
For your dict, you can simply sort with key=lambda x: (x[1], x[0])
For your code, you can also use a Counter from collection
module, like this:
freq = Counter(a)
Related Topics
Beautiful Soup Findall Doesn't Find Them All
Yes' Reporting Error With Subprocess Communicate()
Do Python Regular Expressions Have an Equivalent to Ruby'S Atomic Grouping
How to Detect Collision in Pygame
How to Profile a Python Script
Split Strings into Words With Multiple Word Boundary Delimiters
Sorting List Based on Values from Another List
Get Difference Between Two Lists
What Is the Python "With" Statement Designed For
How to Remove Script Tags With Beautifulsoup
How to Set Your Pythonpath in an Already-Created Virtualenv
Django Server Killed Frequently
Why Do Some Regex Engines Match .* Twice in a Single Input String
What Is the 'Self' Parameter in Class Methods
How to Force Division to Be Floating Point? Division Keeps Rounding Down to 0