Reputation: 34745
I have a dictionary of the form:
d = { 'someText': floatNumber }
Where floatNumber
is an epoch timestamp. I'm trying to organise this such that time is in ascending order.
Example: {'someText':0000001, 'someText1':0000002, and so on}
Only way I can think of doing it is by looping with for k,v in dict.items()
and then manually sorting it into a list but that may take a long time. Any help would be greatly appreciated.
Upvotes: 1
Views: 3335
Reputation: 226346
An order dictionary can be used to store the entries in sorted order:
>>> from collections import OrderedDict
>>> d = OrderedDict(sorted(dict.items(), key=lambda item: item[1]))
Upvotes: 1
Reputation: 14900
First, by default dictionaries are unsorted. You may want to use a list and insert into the appropriate location as you build the dataset. Otherwise, use the sorted
function.
sorted(dict.iteritems(), key=lambda (x, y): y)
Upvotes: 0
Reputation:
from operator import itemgetter
d = {'foo':1, 'bar':3, 'baz':2}
l = [(k, v) for k, v in d.items()]
s = sorted(l, key=itemgetter(1))
# s == [('foo', 1), ('baz', 2), ('bar', 3)]
More on sorting: http://wiki.python.org/moin/HowTo/Sorting
Edit:
Improved version (thanks for the comment):
from operator import itemgetter
d = {'foo':1, 'bar':3, 'baz':2}
s = sorted(d.items(), key=itemgetter(1))
# s == [('foo', 1), ('baz', 2), ('bar', 3)]
Upvotes: 0
Reputation: 816472
Maybe you want:
import operator
values = sorted(d.items(), key=operator.itemgetter(1))
which would generate a sorted list of tuples, like
[('someText', 1), ('someText', 2), ...]
Dictionaries cannot be sorted, so you have to use another data structure to store your key-value pairs.
Upvotes: 4