user1767754
user1767754

Reputation: 25134

Ordered Dict, preserve initial Order

Ordered Dict:

import collections
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))

The above example shows how to order a dict, which is unsupported by nature. However, how can i preserve the initial order rather then sorting by key or value?

Upvotes: 2

Views: 271

Answers (3)

bravmi
bravmi

Reputation: 507

Once you initialized regular dict with your items the order is gone. So just initialize ordered dict in initial order:

import collections as co

co.OrderedDict([(a, b) for a, b in list_of_pairs])
# or
d = co.OrderedDict()
for a, b in list_of_pairs:
    d[a] = b

Upvotes: 1

itzMEonTV
itzMEonTV

Reputation: 20359

Already regular dict has no order when you defining.sort on dict is actually not sorting dict.It is sorting the list containing tuples of (key, value) pairs.

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
s = sorted(d.items(), key=lambda t: t[0])
>>>s
[('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]

This is sorted list of tuples .key = lambda t: t[0] is returning 2nd element of tuple.So sorting based on 2nd element of tuple

new_d = dict(s)
>>>new_d.items()
[('orange', 2), ('pear', 1), ('apple', 4), ('banana', 3)]

That is order disappears.Inoder to maintain order, OrderedDict is used.

For example

>>>OrderedDict({"a":5})
OrderedDict([('a', 5)])

This is also maintaining list of tuples.

So you have to pass a sorted list of tuple

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

Upvotes: 1

101
101

Reputation: 8999

Initial order is preserved for an OrderedDict, so just put it straight in and bypass the regular dictionary:

>>> from collections import OrderedDict
>>> od = OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])

Upvotes: 4

Related Questions