Why is dictionary.keys() a list and not a set?
Duncan Booth
duncan.booth at invalid.invalid
Thu Nov 24 04:01:57 EST 2005
bonono at gmail.com wrote:
> As for the (k,v) vs (v,k), I still don't think it is a good example. I
> can always use index to access the tuple elements and most other
> functions expect the first element to be the key. For example :
>
> a=d.items()
> do something about a
> b = dict(a)
>
> But using the imaginary example :
>
> a = zip(d.values(), d.keys())
> do something about a
> b = dict(a) # probably not what I want.
>
The typical use case for the (v,k) tuple would be when you want sort the
contents of a dictionary by value. e.g. counting the number of occurrences
of each word in a document.
a = zip(d.values(), d.keys())
a.sort()
a.reverse()
print "Today's top 10:"
print str.join(',', [ k for (v,k) in a[:10]])
Ok, so today you can do that another way, but before there was a key
parameter to sort you had to build the tuple somehow:
print str.join(',', sorted(a.iterkeys(),
key=a.__getitem__, reverse=True)[:10])
and the advantage of the latter is of course that it works even when you've
been counting the number of occurences of complex numbers in a document :)
More information about the Python-list
mailing list