Efficiently building ordered dict

Daniel Stutzbach daniel at stutzbachenterprises.com
Mon Feb 22 12:08:08 EST 2010


On Mon, Feb 22, 2010 at 10:32 AM, Bryan <bryanvick at gmail.com> wrote:

> 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)
>

It's not entirely clear what UpdateExistingValue and CreateNewValue do.
However, it looks like you are trying to create a dictionary where the keys
are sorted.  Is that right?

If so, you could use the sorteddict type from my blist package, which is
similar to an OrderDict except it efficiently keeps the keys in sorted order
instead of insertion order.  For example:

>>> from blist import sorteddict
>>> my_dict = sorteddict({1: 'a', 6: 'b', -5: 'c'})
>>> my_dict.keys()
[-5, 1, 6]
>>> my_dict[2] = 'd'
>>> my_dict.keys()
[-5, 1, 2, 6]

It's available here:
http://pypi.python.org/pypi/blist/
--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC <http://stutzbachenterprises.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100222/84282e08/attachment-0001.html>


More information about the Python-list mailing list