Python Ordereddict: Sort By Tuple Order?
So I have this dictionary, which I'm converting to OrderedDict. On conversion, I'd like to sort the OrderedDict by the order in which its keys appear in a separate tuple. Any oth
Solution 1:
Another method which is a bit simpler than sorting is to create an OrderedDict
from the titles, then update the OrderedDict
from your original dict
:
from collections importOrderedDictd= {
'spam': 'tasty',
'subtitle': 'A Subtitle',
'title': 'Test Title',
'foo': 'bar',
}
key_order = ('title', 'subtitle')
od = OrderedDict((k, d[k]) for k in key_order)
od.update(d)
Or as tzaman suggests in comments, as the values will always be set on the following update, you can construct the original OrderedDict
with:
od = OrderedDict.fromkeys(key_order)
od.update(d)
Solution 2:
ordered_dict = OrderedDict(sorted(dict.items(),
key=lambda x: key_order.index(x[0])if x[0] in key_order else 10e10 ))
This uses a key of the index of the given item in the key order. If it isn't found, it uses a large number instead, putting it at the end. It produces the following OrderedDict
:
OrderedDict([('title', 'Test Title'), ('subtitle', 'A Subtitle'), ('foo', 'bar'), ('spam', 'tasty')])
foo
is before spam
because the original dictionary had an arbitrary order.
Solution 3:
from collections import OrderedDict
d = {
'spam': 'tasty',
'subtitle': 'A Subtitle',
'title': 'Test Title',
'foo': 'bar',
}
key_order = ('title', 'subtitle')
key_order = OrderedDict((k, i) for i, k inenumerate(key_order))
ordered_dict = OrderedDict(sorted(d.iteritems(), key=lambda k: key_order.get(k[0], float("inf"))))
Use items()
instead of iteritems()
in python 3.
Post a Comment for "Python Ordereddict: Sort By Tuple Order?"