Efficiently building ordered dict

Arnaud Delobelle arnodel at googlemail.com
Mon Feb 22 13:09:31 EST 2010


Bryan <bryanvick at gmail.com> writes:

> 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?
>
> unorderedDict = {}
> for thing in unorderedList:
> 	if thing.id in unorderedDict:
> 		UpdateExistingValue(unorderedDict[thing.id])
> 	else:
> 		CreateNewValue(unorderedDict[thing.id])
>
> orderedDict = OrderedDict()
> for k in sorted(unorderedDict.keys()):
> 	orderedDict[k]  unorderedDict.pop(k)

Why don't you sort your unorderedList first then simply create your
orderedDict?

To me your problem is stated in too vague terms anyway and the code you
post could not really work as unorderedDict is bound to remain empty
whatever the values of all the other names.

At any rate, why do you need an ordered dictionary?  It seems suspect to
me as you sort the keys before inserting the items.

-- 
Arnaud



More information about the Python-list mailing list