dictionary issue (and maybe PEP ... depending on the answer)

Steven Taschuk staschuk at telusplanet.net
Mon Jun 2 09:03:21 CEST 2003

Quoth dsavitsk:
>  >>> [_months[i] for i in _months.keys()]
> The issue is, this consistently returns the months in order. [...]

Heh.  Normally we get people complaining about dicts *not*
providing items in order.

> [...] I don't see 
> any obvious reason that it does, but I can't get it to fail. So,I am 
> wondering if there is a reason, or is it serendipity.

Perhaps the following previous post of mine will make clear why it
happens with this data:

I'd discourage you from relying on this in your code, and
especially from relying on it implicitly.  Something like

    months = [(1, 'January'),
              (2, 'February'),
              # ...
    monthdict = dict(months)
    monthnames = [name for number, name in months]

also guarantees the ordering of monthnames, but makes that
guarantee not only resistant to any future change of the dict
implementation, but also clear to the reader.

> Assuming that there is not a good reason, the PEP idea is adding a 
> sorted_keys() method to dictionaries which would just return the keys in 
> the same order they would be in by doing this.
>  >>> l = d.keys()
>  >>> l.sort()
> The advantage is that using dictionary keys in list comprehensions would 
> be easier, but other than that it is not too big a deal.

I'd be -1 on this, fwiw.  It's rarely needed in my experience;
when order really does matter, I'd use a list anyway; if I really
need a dict and don't want to use a list, writing
    def sort(iterable):
        L = list(iterable)
        return L
and asking for
is just as easy.  And it's just one more thing for dict-like
objects to implement.

Steven Taschuk                          staschuk at telusplanet.net
"Its force is immeasurable.  Even Computer cannot determine it."
                           -- _Space: 1999_ episode "Black Sun"

More information about the Python-list mailing list