[Python-Dev] Proposal: dict.with_values(iterable)
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.
> > with_values(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.with_values(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?
> > 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.from_keys_and_values(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.from_keys_and_values(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
I think it is possible.
> I'm fine with dict.with_values() API, but I'm asking if it could be
> written differently.
I implemented it as instance method of dict
because it may modify the dict internally (at first invocation).
Inada Naoki <songofacandy at gmail.com>