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 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)
Sorting a dictionary by value then by key
In [62]: y={100:1, 90:4, 99:3, 92:1, 101:1}
In [63]: sorted(y.items(), key=lambda x: (x[1],x[0]), reverse=True)
Out[63]: [(90, 4), (99, 3), (101, 1), (100, 1), (92, 1)]
The key=lambda x: (x[1],x[0])
tells sorted
that for each item x
in y.items()
, use (x[1],x[0])
as the proxy value to be sorted. Since x
is of the form (key,value)
, (x[1],x[0])
yields (value,key)
. This causes sorted
to sort by value
first, then by key
for tie-breakers.
reverse=True
tells sorted
to present the result in descending, rather than ascending order.
See this wiki page for a great tutorial on sorting in Python.
PS. I tried using key=reversed
instead, but reversed(x)
returns an iterator, which does not compare as needed here.
python sort dictionary items by value and then key
MyDict = {0: {'Score': 80.0, 'studentName': 'dan'},
1: {'Score': 92.0, 'studentName': 'rob'},
2: {'Score': 10.0, 'StudentName': 'xyz'}}
This returns the list of key-value pairs in the dictionary, sorted by value from highest to lowest:
sorted(MyDict.items(), key=lambda x: x[1], reverse=True)
For the dictionary sorted by key, use the following:
sorted(MyDict.items(), reverse=True)
The return is a list of tuples because dictionaries themselves can't be sorted.
This can be both printed or sent into further computation.
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));
Building a list of dictionary values, sorted by key
This code:
keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
result.append(attributes[key])
Is basically the use case for which list comprehensions were invented:
result = [attributes[key] for key in sorted(attributes.keys(), reverse=True)]
Sort Dictionary by keys
let dictionary = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]
EDIT:
The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary'
is also a 'CollectionType'
of (key, value) pairs and we can use the global 'sorted'
function to get a sorted array containg both keys and values, like this:
let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]
EDIT2: The monthly changing Swift syntax currently prefers
let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]
The global sorted
is deprecated.
How do I sort a dictionary by key?
Note: for Python 3.7+, see this answer
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict
in a way that would preserve the ordering.
The easiest way is to use OrderedDict
, which remembers the order in which the elements have been inserted:
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Never mind the way od
is printed out; it'll work as expected:
In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
Python 3
For Python 3 users, one needs to use the .items()
instead of .iteritems()
:
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
Related Topics
Inter-App Data Migration (Migrating Data to New App Version)
How to Update the Constant Height Constraint of a Uiview Programmatically
Rounding a Double Value to X Number of Decimal Places in Swift
Protocol Doesn't Conform to Itself
What Is an Optional Value in Swift
Firestore: How to Get Random Documents in a Collection
Swift 3 Incorrect String Interpolation With Implicitly Unwrapped Optionals
Any Way to Replace Characters on Swift String
How to Deal With @Objc Inference Deprecation With #Selector() in Swift 4
Is Swift Pass by Value or Pass by Reference
How Does One Generate a Random Number in Swift
Difference Between 'Let' and 'Var' in Swift
Nsdate() or Date() Shows the Wrong Time
How to Check If a String Contains Another String in Swift
Structure VS Class in Swift Language