set, dict and other structures

Simo Melenius firstname.lastname at iki.fi-spam
Wed Feb 2 17:18:27 EST 2005


"Giovanni Bajo" <noway at sorry.com> writes:

> Just today I was writing some code where I wanted to use sets for
> the abstraction (intersection, etc.), but also carry some values
> with them to process. So, yes, I believe that having set-like
> abstraction for dictionaries would be great. In fact, for a moment I
> wondered if dict.keys() was already of type set in 2.4, because it
> could have made sense.

Which sets you need depends on each case, so a generic set-ified
extension would be both limited and potentially confusing. For
example, a set of (key,value) tuples is the simplest and unambiguous.
On the other hand, if the values differ you really just need a set of
keys and then you can do the value lookup and collision handling
yourself using the result set as keys to both of your dictionaries.
You could subclass dict to provide aliases such as:

dict.itemset ()
dict.keyset ()
dict.valueset ()

for the following if these look overly bloated to you:

set (dict.iteritems ())
set (dict.iterkeys ())
set (dict.itervalues ())

For example:

py> for k,v in set (d1.iteritems ()) - set (d2.iteritems ()):
py>   print k, v

looks quite concise and self-explanatory to me already. A _notable_
performance gain would probably justify native set-ifying getters,
especially if there indeed were implementation-level data structures
to share.


br,
S



More information about the Python-list mailing list