[Python-Dev] Proposal: dict.with_values(iterable) (original) (raw)

Inada Naoki songofacandy at gmail.com
Fri Apr 12 12:07:23 EDT 2019


On Fri, Apr 12, 2019 at 11:31 PM Victor Stinner <vstinner at redhat.com> wrote:

Nice optimization! I have questions on the proposed API. > withvalues(self, iterable, /) > Create a new dictionary with keys from this dict and values from iterable. > > When length of iterable is different from len(self), ValueError is raised. > This method does not support dict subclass. In short, mydict.withvalues(values) behaves as dict(zip(mydict.keys(), values)), but is more efficient?

Yes. But unlike zip, keys() and values must have exactly same length.

The method rely on the fact that dict is preserving key insertion order, right?

Yes.

> This might be usable for: > > * csv.DictReader > * namedtuple.asdict() > * DB-API 2.0 implementations: (e.g. DictCursor of mysqlclient-python)

I guess that a new dict constructor taken keys and values like dict.fromkeysandvalues(keys, values) would work, but would not benefit from the dict key-sharing optimization?

I don't like more overloading. And this API is specialized to build multiple dicts, not one dict. So I want to have dedicated API for it.

Would it be possible to implement the key-sharing optimization using a dict.fromkeysandvalues(mydict.keys(), values) method: detect that keys are owned by a dict, and so create a new dict linked to the keys dict? A dict view contains a reference to the iterated dict (dictiterobject.didict).

I think it is possible.

I'm fine with dict.withvalues() API, but I'm asking if it could be written differently. Victor

I implemented it as instance method of dict because it may modify the dict internally (at first invocation).

-- Inada Naoki <songofacandy at gmail.com>



More information about the Python-Dev mailing list