Dictionary from list?
Tim Peters
tim.one at home.com
Sat Oct 27 13:16:43 EDT 2001
[Terry Reedy]
> Fact: a Python dictionary literal is a sequence of key:value pairs of
> literals, with the first becoming a hashable object, and only such a
> sequence.
Sounds more like a definition than a fact <wink>.
> Observation: ':' is analogous to '( , )', which could have been the
> syntax chosen (though I'm glad it wasn't).
>
> Therefore:
>
> Proposed rule 1: the dictionary() constructor should accept a sequence
> of pairs of objects, with the first being keyable (hashable). In
> particular, it should invert dict.items.
In current CVS, it does. In 2.2-speak, it accepts an iterable object
producing iterable objects producing exactly 2 objects. It also accepts a
mapping object (as it did in 2.2b1), and also accepts nothing (ditto -- it
returns {} then, much as list() returns [] and tuple() returns ()).
> Note: by type, 'pair' might mean duple only; by interface, it would
> mean an object reporting a length of two and yielding objects with
> indexes 0 and 1.
"By interface" is important, but the details there are off for 2.2 --
iterable objects don't have to support len or indexing. For example,
class AddressBookEntry:
# with .firstname, .lastname attributes
...
def __iter__(self):
return iter((self.firstname, self.lastname))
A sequence of AddressBookEntry instances is OK to pass to dictionary(),
despite that an AddressBookEntry defines neither __len__ nor __getitem__. A
generator yielding instances of AddressBookEntry is also fine; etc.
> Comment: once pair is defined, this rule gives a uniform target for
> conversion from other formats, including those generated by other
> software systems. I currently vote for the latter.
I didn't understand "the latter" here, unless it's a vote for "other
software systems", in which case I'm keen to see the patch <wink>.
> Proposed rule 2: dictionary() should reject any other sequence, just
> as does the internal constructor-from-literals.
"Sequence" is a slippery word. dictionary() continues to accept a mapping
object too. Of course, "mapping object" is also a slippery phrase.
> Paraphrase: conversions from the many other possible formats should be
> handled externally from dictionary().
Indeed, we're going to cheerfully endure abuse for sticking to that.
> Opinion 3: Given the fact and comments above, these two rules should
> be easy to understand and teach.
Yup.
More information about the Python-list
mailing list