Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}  # doesn't work

In Python 2.6 and earlier, the dict constructor can receive an iterable of key/value pairs:

d = dict((key, value) for (key, value) in iterable)

From Python 2.7 and 3 onwards, you can just use the dict comprehension syntax directly:

d = {key: value for (key, value) in iterable}

Of course, you can use the iterable in any way you want (tuples and lists literals, generator comprehensions, list comprehensions, generator functions, functional composition... feel creative) as long as each element is an iterable itself of two elements:

d = {value: foo(value) for value in sequence if bar(value)}

def key_value_gen(k):
   yield chr(k+65)
   yield chr((k+13)%26+65)
d = dict(map(key_value_gen, range(26)))

In Python 3 / Python 2.7+ dict comprehensions works like this:

d = {k:v for k, v in iterable}

For Python 2.6 and earlier, see fortran's answer.


事实上,如果它已经理解了某种映射,那么你甚至不需要迭代iterable,这个dict构造器会为你优雅地做它:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}
链接地址: http://www.djcxy.com/p/5152.html

上一篇: JavaScript字符串是不可变的吗? 我需要JavaScript中的“字符串生成器”吗?

下一篇: 在Python中创建一个包含列表理解的词典