gandolf
gandolf

Reputation: 3444

Sorting a dictionary with list values

I'm pulling some data from a redis key-value store. The data is in the format of a list. However Im pulling them and placing them into a dictionary

{ name1: [ int1, int2] }
{ name2: [ int11,int22]}
..etc...

I want to create a sorted dictionary where the entries pulled are sorted by int2 value in the list. How can I do this sorted and itemgetter?

So as a result I'd like a sorted dictionary such that names are sorted according to the value of int2 of the list values in descending order

I tried sorted(data, key=itemgetter(2)) but this obviously did not work :(

Upvotes: 0

Views: 54

Answers (3)

Iron Fist
Iron Fist

Reputation: 10951

As per Python Docs

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

So, you cannot get an ordered dictionary, if you want to keep the same data type ,i.e: dictionary and order the items, use OrderedDict:

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

So if you want to get an ordered dictionary sorted by int2 (Example from Python docs)

from collections import OrderedDict

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

d = OrderedDict(sorted(d.items(), key=lambda t: t[1])) #Order by Value

print d

Output:

OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

Upvotes: 0

Daniel
Daniel

Reputation: 42748

To get a sorted list of all names, you have to get the value to your key:

sorted_names = sorted(data, key=lambda k: data[k][1])

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90869

You can try -

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

This would return tuples sorted by the second element in the list of value of the dictionary.

Please note, dictionary does not have a concept of order in its elements , that is you cannot sort a dictionary per se.

Upvotes: 1

Related Questions