Efficiently building ordered dict

Arnaud Delobelle arnodel at googlemail.com
Mon Feb 22 23:10:47 CET 2010

On 22 Feb, 21:29, Bryan <bryanv... at gmail.com> wrote:
> Sorry about the sorted != ordered mix up.  I want to end up with a
> *sorted* dict from an unordered list.  *Sorting the list is not
> practical in this case.*  I am using python 2.5, with an ActiveState
> recipe for an OrderedDict.

Why does the dict need to be sorted?
Why is it impractical to sort the list, but practical to sort the

Whithout knowing this, it is difficult to get an idea of your problem
an a potential solution.

> My solution is to create a regular dict from the list.  Then sort the
> keys, and add the keys+values to an OrderedDict.  Since the keys are
> being added to the OrderedDict in the correctly sorted order, at the
> end I end up with a OrderedDict that is in the correctly *sorted*
> order.
> self.accTotals = {}
> for row in self.rows:
>         if row.acc.code in self.accTotals:
>                 self.accTotals[row.acc.code].addRow(row)
>         else:
>                 accSummary = Total()
>                 accSummary.addRow(row)
>                 self.accTotals[row.acc.code] = accSummary
> self.accTotals = self._getOrderedDict(self.accTotals)

This code is a typical example where defaultdict, which was added in
Python 2.5 [1],  would be of use:

accTotals = defaultdict(Total)
for row in self.rows:
self.accTotals = self._getOrderedDict(accTotals)

However, as you don't explain what self._getOrderedDict(...) does, it
is quite difficult to guess how to improve it!

[1] http://docs.python.org/library/collections.html#collections.defaultdict

More information about the Python-list mailing list