Efficiently building ordered dict

MRAB python at mrabarnett.plus.com
Mon Feb 22 19:04:20 CET 2010

Bryan wrote:
> On Feb 22, 9:19 am, MRAB <pyt... at mrabarnett.plus.com> wrote:
>> Bryan wrote:
>>> I am looping through a list and creating a regular dictionary.  From
>>> that dict, I create an ordered dict.  I can't think of a way to build
>>> the ordered dict while going through the original loop.  Is there a
>>> way I can avoid creating the first unordered dict just to get the
>>> ordered dict?  Also, I am using pop(k) to retrieve the values from the
>>> unordered dict while building the ordered one because I figure that as
>>> the values are removed from the unordered dict, the lookups will
>>> become faster.  Is there a better idiom that the code below to create
>>> an ordered dict from an unordered list?
>> Why are you building a dict from a list and then an ordered dict from
>> that? Just build the ordered dict from the list, because it's behaves
>> like a dict, except for remembering the order in which the keys were
>> added.
> Could you write some pseudo-code for that?  I'm not sure how I would
> add the items to the OrderedDict while looping through the list.
> Wouldn't the list need to be sorted first (which in this case isn't
> practical)?
ordered != sorted.

If you want the ordered dict to be sorted by key then build a dict first
and then create the ordered dict from the sorted dict. I think the
quickest way to build the sorted dict is:

     orderedDict = OrderedDict(sorted(unorderedDict.items()))

although I haven't tried 'sorteddict' (see Daniel Stutzbach's post).

More information about the Python-list mailing list