我可以使用列表理解语法来创建词典吗?

例如,通过迭代成对的键和值:

d = {... for k, v in zip(keys, values)}

当前回答

在Python 2.7中,它类似于:

>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}

给他们拉链!

其他回答

Python版本>=2.7,请执行以下操作:

d = {i: True for i in [1,2,3]}

Python版本<2.7(RIP,2010年7月3日-2019年12月31日),请执行以下操作:

d = dict((i,True) for i in [1,2,3])

要添加到@fortran的答案中,如果您想要遍历键列表key_list以及值列表value_list:

d = dict((key, value) for (key, value) in zip(key_list, value_list))

or

d = {(key, value) for (key, value) in zip(key_list, value_list)}

在Python 3和Python 2.7+中,字典理解如下所示:

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

对于Python 2.6或更早版本,请参见fortran的答案。

这种方法使用for循环对给定日期进行迭代。

Syntax: {key: value for (key, value) in data}

Eg:

# create a list comprehension with country and code:
    Country_code = [('China', 86), ('USA', 1),
            ('Ghana', 233), ('Uk', 44)]

# use iterable method to show results
{key: value for (key, value) in Country_code}

是的,这是可能的。在python中,理解可以用于列表、集合、字典等。你可以这样写

mydict = {k:v for (k,v) in blah}

使用条件语句和循环的字典理解的另一个详细示例:

parents = [father, mother]
            
parents = {parent:1 - P["mutation"] if parent in two_genes else 0.5 if parent in one_gene else P["mutation"] for parent in parents}