Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort dict by value python [duplicate]

Assume that I have a dict.

data = {1:'b', 2:'a'} 

And I want to sort data by 'b' and 'a' so I get the result

'a','b' 

How do I do that?
Any ideas?

like image 233
kingRauk Avatar asked May 27 '13 11:05

kingRauk


People also ask

Can you sort a dictionary Python by value?

Older PythonIt 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.

How do you sort a dictionary by value first and then by key Python?

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

Does Dict allow duplicates in Python?

As you can see in the Screenshot, the output displays the dictionary but it does not have duplicate keys in a dictionary because in Python dictionary does not allow duplicate keys. If you want to get all those values from a list and store them in the dictionary then you have to use the unique key with every value.


2 Answers

To get the values use

sorted(data.values()) 

To get the matching keys, use a key function

sorted(data, key=data.get) 

To get a list of tuples ordered by value

sorted(data.items(), key=lambda x:x[1]) 

Related: see the discussion here: Dictionaries are ordered in Python 3.6+

like image 178
John La Rooy Avatar answered Sep 22 '22 05:09

John La Rooy


If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict

>>> from collections import OrderedDict >>> from operator import itemgetter >>> data = {1: 'b', 2: 'a'} >>> d = OrderedDict(sorted(data.items(), key=itemgetter(1))) >>> d OrderedDict([(2, 'a'), (1, 'b')]) >>> d.values() ['a', 'b'] 
like image 28
jamylak Avatar answered Sep 20 '22 05:09

jamylak