Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

Paddy paddy3118 at netscape.net
Sun Jul 2 03:10:43 EDT 2006


vatamane at gmail.com wrote:
> This has been bothering me for a while. Just want to find out if it
> just me or perhaps others have thought of this too: Why shouldn't the
> keyset of a dictionary be represented as a set instead of a list?

I think the order of the items returned by keys() and values() are
related. I decided on a short  empirical test:

>>> import random
>>> n=50
>>> d = dict((i,random.randint(0,n-1)) for i in range(n))
>>> k,v = d.keys(), d.values()
>>> [d[k[i]] == v[i]  for i in range(n)]
[True, True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True, True, True,
True, True, True]
>>> ## for larger n try
>>> # False in [d[k[i]] == v[i]  for i in range(n)]

The order of keys() and the order of values() are related, so a change
to returning sets would also loose this functionality.

Mind you, Never rely on that implied ordering. Always use items().

And so *if* sets were returned for keys() and values() then it should
for items() too.

- Paddy.




More information about the Python-list mailing list