How to Sort a Dictionary by Key

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

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)

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 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)

How to sort dictionaries by keys in Python

Dicts don't have an order.

You can call sorted but this just gives you a sorted list of the keys:

>>> sorted(d)
['a', 'b', 'c', 'd']

You can treat it as an iterable and sort the key-value tuples, but then you've just got a list of tuples. That's not the same as a dict.

>>> sorted(d.items())
[
('a', [1, 2, 3]),
('b', ['blah', 'bhasdf', 'asdf']),
('c', ['one', 'two']),
('d', ['asdf', 'wer', 'asdf', 'zxcv'])
]

If you are using Python 2.7 or newer you could also consider using an OrderedDict.

dict subclass that remembers the order entries were added

For example:

>>> d = collections.OrderedDict(sorted(d.items()))
>>> for k, v in d.items():
>>> print k, v

a [1, 2, 3]
b ['blah', 'bhasdf', 'asdf']
c ['one', 'two']
d ['asdf', 'wer', 'asdf', 'zxcv']

Sort dictionary alphabetically when the key is a string (name)

simple algorithm to sort dictonary keys in alphabetical order, First sort the keys using sorted

sortednames=sorted(dictUsers.keys(), key=lambda x:x.lower())

for each key name retreive the values from the dict

for i in sortednames:
values=dictUsers[i]
print("Name= " + i)
print (" Age= " + values.age)
print (" Address= " + values.address)
print (" Phone Number= " + values.phone)

How to sort dictionary keys by their appearance in a file

If you want to sort the list associated with each fruit, you could do the following:

>>> mydict = {k : sorted(v, key=lambda x : int(x[0])) for k, v in mydict.items()}
>>> mydict

{'orange': [['1', '00:00:03,950'],
['9', '00:00:24,030'],
['11', '00:00:29,640']],
'cherry': [['20', '00:00:54,449']],
'apple': [['14', '00:00:38,629']],
'banana': [['2', '00:00:06,840'],
['3', '00:00:09,180'],
['4', '00:00:10,830']]}

This is iterating over the key value pairs of the dictionary, and sorting the elements of each value by the int of their first element.

But to be clear, as of Python 3.7, the normal dict is ordered. So here, you see that the fruit names are appearing in the same ordered they were created - in earlier Python this wasn't the case.

You also say you want to sort the keys (the fruit names), but it looks like you want to sort the values (the line numbers and timestamps). If you want to additionally sort the fruit names, you could throw sorted on the call to get the items:

>>> mydict = {k : sorted(v, key=lambda x : int(x[0])) for k, v in sorted(mydict.items())}
>>> mydict

{'apple': [['14', '00:00:38,629']],
'banana': [['2', '00:00:06,840'],
['3', '00:00:09,180'],
['4', '00:00:10,830']],
'cherry': [['20', '00:00:54,449']],
'orange': [['1', '00:00:03,950'],
['9', '00:00:24,030'],
['11', '00:00:29,640']]}

# now mydict's keys are in alphabetical order, and its values are also ordered by line number

Sort dictionary by keys in Swift

Dictionary already has a sorted method that takes a closure that defines the sorting function. You can sort by keys in the closure, then simply map over the resulting tuples to get the values only.

let sortedDictKeys = dict.sorted(by: { $0.key < $1.key }).map(\.value)


Related Topics



Leave a reply



Submit