access dictionary with preferred order ?

Fredrik Lundh fredrik at pythonware.com
Sat Oct 22 09:03:57 EDT 2005


bonono at gmail.com wrote:

> I am wondering if there is a dictionary data type that allows me to
> define the order of access when iterating it using items/keys etc. ?
>
> An example:
>
> a=dict(a=dict(), c=dict(), h=dict())
> prefer=['e','h', 'a']
>
> for x in a.values: print x
>
> would give me
> {h:dict()}, {a:dict()}, then the rest which I don't care about the
> order ?

a straight-forward implementation should be pretty efficient:

    for k in prefer:
        try:
            v = d.pop(k)
        except KeyError:
            pass
        else:
            ... deal with k, v ...
    for k, v in d.iteritems():
        ... deal with k, v ...

or, non-destructive:

    for k in prefer:
        try:
            v = d[k]
        except KeyError:
            pass
        else:
            ... deal with k, v ...
    for k, v in d.iteritems():
        if k not in prefer:
            ... deal with k, v ...

the latter is trivial to convert into a helper generator:

    def ordered_items(d, prefer):
        for k in prefer:
            try:
                v = d[k]
            except KeyError:
                pass
            else:
                yield k, v
        for k, v in d.iteritems():
            if k not in prefer:
                yield k, v

    for k, v in ordered_items(d, prefer):
        ... deal with k, v ...

if you insist on having this behaviour in a type rather than a helper,
subclass dict and add ordered_items as a method.

</F>






More information about the Python-list mailing list