在Python中创建列表解析的字典 [英] Create a dictionary with list comprehension in Python
问题描述
我喜欢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
推荐答案
Python 2.6和更早版本,dict构造函数可以接收一个可重复的键/值对:
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)
从Python 2.7和3开始,你可以使用直接词汇理解语法:
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)))
这篇关于在Python中创建列表解析的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!