4 ms·
> 9. Create dict from keys and values using zip In 2.7+, I'd recommend a dictionary comprehension instead.
by simon_weber 13y ago
> 9. Create dict from keys and values
using zip
In 2.7+, I'd recommend a dictionary comprehension instead.
- aaren 13y agoIn this case, {k: v for k, v in zip(keys, values)} edit: As I mention below, this becomes useful when you want to do e.g. {f(k): g(v) for k, v in zip(keys, values)}
- epistasis 13y agoI'd disagree, as dict(zip(keys, value)) is more concise, doesn't introduce extra variables, and doesn't repeat itself, and explicitly names a dict rather than using a symbol.
- herge 13y agoRight, but the second you need to modify either the key or the value, you are better off with the dict comprehension. It's like map() vs [...].
- aaren 13y agoI like list comprehensions and to me dict comprehensions feel like a natural extension of this. It means that you can do things like {k.upper(): v ** 2 for k, v in zip(keys, values)} Or generally {f(k): g(v) for k, v in zip(keys, values)} I find this very extensible. In terms of conciseness, they both fit on a single line and I like the whitespace inside a dict comprehension.
- Walkman 13y ago"Simple is better than complex."