Efficiently building ordered dict

Shashwat Anand anand.shashwat at gmail.com
Mon Feb 22 17:55:55 CET 2010

OrderedDict is a class in collection module in python 2.7a3+. Perhaps you
can use it from there.

>>> dir(collections)
['Callable', 'Container', 'Counter', 'Hashable', 'ItemsView', 'Iterable',
'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping',
'MutableSequence', 'MutableSet', 'OrderedDict', 'Sequence', 'Set', 'Sized',
'ValuesView', '_Link', '__all__', '__builtins__', '__doc__', '__file__',
'__name__', '__package__', '_abcoll', '_chain', '_eq', '_heapq', '_ifilter',
'_imap', '_iskeyword', '_itemgetter', '_proxy', '_repeat', '_starmap',
'_sys', 'defaultdict', 'deque', 'namedtuple']


On Mon, Feb 22, 2010 at 10:02 PM, Bryan <bryanvick at gmail.com> 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?
> 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)
> --
> http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100222/b0306e1b/attachment.html>

More information about the Python-list mailing list