Why is dictionary.keys() a list and not a set?
Christoph Zwerschke
cito at online.de
Thu Nov 24 10:34:11 EST 2005
Mike Meyer wrote:
> Are you sure dict.values() should be a set? After all, values aren't
> guaranteed to be unique, so dict(a = 1, b = 1).values() currently
> returns [1, 1], but would return set([1]) under your proposal.
Good point. Contrary to the keys, the values are not unique. Still, it
would make sense to only return the set (the value set of the mapping)
because this is usually what you are interested in and you'd think the
information about which value belongs to which key is lost anyway.
However (see other postings in this thread) this last statement is
wrong: If you call keys() and values() consecutively, then they are
guaranteed to correspond to each other. If values() would return a set,
this would be completely broken.
> What about dict.items()?
Actually, if keys() would be a set, this should return a set, too (the
set of key/value tuples).
>>For instance, by allowing the set operator "in" for dictionaries,
>>instead of "has_key".
> "in" already works for dicdtionaries:
I know. I wanted to use it as an example where set operations have
already been made available for dictionaries.
I know, 'in' has existed for lists and tuples long before sets, but
actually it is a native set operation.
From a mathematical point of view, it would have been nice if Python
had defined "set" as a basic data type in the beginning, with lists,
tuples, dictionaries as derived data types.
By the way, i wonder why the common mathematical notation { 1,2,3 } was
not allowed for set((1,2,3)). It would not clash with the dictionary
notation which requires additional colons.
-- Christoph
More information about the Python-list
mailing list