Reputation: 9792
How to sort this dictionary by 'votes'
in Python?
{
1 : {
'votes' : 2,
'id' : 10
},
2 : {
'votes' : 10,
'id' : 12
},
3 : {
'votes' : 98,
'id' : 14
}
}
To results in:
{
3 : {
'votes' : 98,
'id' : 14
},
2 : {
'votes' : 10,
'id' : 12
},
1 : {
'votes' : 2,
'id' : 10
}
}
Upvotes: 1
Views: 216
Reputation: 531
You could also sort the items in the dictionary:
print sorted(d.items(), key=lambda x: x[1]['votes'], reverse=True)
like Francis' suggestion, but you know the original key for every item.
Upvotes: 0
Reputation: 31621
Standard dictionaries do not have an order, so sorting them makes no sense. Both those dictionaries are exactly the same.
Perhaps what you really want is a list?
aslist = originaldict.values()
aslist.sort(key=lambda item:item['votes'], reverse=True)
This will extract the items from your dict as a list and resort the list by votes
.
Upvotes: 0
Reputation: 208475
Dictionaries are unsorted, if you want to be able to access elements from you dictionary in a specific order you can use an OrderedDict
as in jcollado's answer, or just sort the list of keys by whatever metric you are interested in, for example:
data = {1: {'votes': 2, 'id': 10}, 2: {'votes': 10, 'id': 12}, 3: {'votes': 98, 'id': 14}}
votes_order = sorted(data, key=lambda k: data[k]['votes'], reverse=True)
for key in votes_order:
print key, ':', data[key]
Output:
3 : {'votes': 98, 'id': 14}
2 : {'votes': 10, 'id': 12}
1 : {'votes': 2, 'id': 10}
Upvotes: 3
Reputation: 40384
You could use an OrderedDict
:
>>> from collections import OrderedDict
>>> od = OrderedDict(sorted(d.items(),
key=lambda t: t[1]['votes'],
reverse=True))
>>> od
OrderedDict([(3, {'votes': 98, 'id': 14}),
(2, {'votes': 10, 'id': 12}),
(1, {'votes': 2, 'id': 10})])
where d
is your original dictionary.
Upvotes: 4