[Python-ideas] Dict(x, y) -> Dict(zip(x, y))

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Feb 14 19:30:57 EST 2016


I often find myself writing dict(zip(x, y)). Maybe that's just me or
maybe not but I would like it if it were possible to spell that simply
as dict(x, y).

Currently dict() with two arguments is an error:

$ python3
Python 3.4.3 (default, Mar 26 2015, 22:03:40)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dict(['foo', 'bar'], [1, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: dict expected at most 1 arguments, got 2

I would prefer it if dict(x, y) would treat x as an iterable of keys
and y as an iterable of corresponding values. This would be
semantically equivalent to dict(zip(x, y)) except that it would raise
an error if x and y don't yield the same number of items (zip
truncates the longer argument).

Although mostly equivalent the new construction might be more
efficient, would reduce the visual noise of the redundant call to zip,
and would be slightly more robust to errors.

--
Oscar


More information about the Python-ideas mailing list