我可以使用列表理解语法来创建词典吗?
例如,通过迭代成对的键和值:
d = {... for k, v in zip(keys, values)}
我可以使用列表理解语法来创建词典吗?
例如,通过迭代成对的键和值:
d = {... for k, v in zip(keys, values)}
当前回答
这种方法使用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}
其他回答
事实上,如果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}
下面是使用字典理解创建字典的另一个示例:
我在这里要做的是创建一个字母表字典,其中每一对;是英文字母及其在英文字母表中的对应位置吗
>>> import string
>>> dict1 = {value: (int(key) + 1) for key, value in
enumerate(list(string.ascii_lowercase))}
>>> dict1
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8,
'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's':
19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
>>>
注意这里使用enumerate获取列表中的字母表及其索引,并交换字母表和索引以生成字典的键值对
希望它能给你一个字典压缩的好主意,并鼓励你经常使用它,使你的代码更紧凑
这种方法使用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 3和Python 2.7+中,字典理解如下所示:
d = {k:v for k, v in iterable}
对于Python 2.6或更早版本,请参见fortran的答案。
是的,这是可能的。在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}