2018년 1월 8일 월요일

Python dictionary sorting by values

To sort we may use (1) list.sort() : sort method for list  
(2) sorted(iterable) : sorted function for iterables

In case of dictionary, sorted(dictionary) by default sort in keys. 
In other words, in order of dictionary.keys()

To sort by values of a dictionary, one have to use key=function argument in sorted.

For example:
dict={ a: 3, b: 1, c: 2}

sorted(dict) gives [a,b,c]

We may define a function or use lambda function to sort by value

sorted(dict, key= lambda x: dict[x])  gives [b,c,a]

In case of dictionary of dictionary, we may use dictionary.items() as iterables.

mydict={ a: { age:10 }, b: {age:3}, c:{age:5} }

def getV(x):                  # dictionary.items gives tuple of key and value
    return x[1]['age']         
sorted(mydict.items(), key=getV)

or 

sorted(mydict.keys(), key= lambda x:mydict[x]['age']) 


 

댓글 없음:

댓글 쓰기