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

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

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

当前回答

试试这个,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

假设我们有两个列表国家和首都

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

然后从两个列表中创建字典:

print get_dic_from_two_lists(country, capital)

输出是这样的,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}

其他回答

使用字典理解(Python 2.7及更高版本):

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

对于更简单的情况或更早版本的Python,也可以使用dict构造函数,例如:

pairs = [('a', 1), ('b', 2)]
dict(pairs)                         #=> {'a': 1, 'b': 2}
dict([(k, v+1) for k, v in pairs])  #=> {'a': 2, 'b': 3}

给定单独的键和值数组,使用带有zip的dict构造函数:

keys = ['a', 'b']
values = [1, 2]
dict(zip(keys, values))  #=> {'a': 1, 'b': 2}
2) "zip'ped" from two separate iterables of keys/vals
dict(zip(list_of_keys, list_of_values))

试试这个,

def get_dic_from_two_lists(keys, values):
    return { keys[i] : values[i] for i in range(len(keys)) }

假设我们有两个列表国家和首都

country = ['India', 'Pakistan', 'China']
capital = ['New Delhi', 'Islamabad', 'Beijing']

然后从两个列表中创建字典:

print get_dic_from_two_lists(country, capital)

输出是这样的,

{'Pakistan': 'Islamabad', 'China': 'Beijing', 'India': 'New Delhi'}

这段代码将使用列表理解为多个列表创建字典,这些列表具有可用于pd.DataFrame()的不同值

#Multiple lists 
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]

#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}

#Convert dict to dataframe
df=pd.DataFrame(data)
display(df)

enumerate将向vals传递n,以使每个键与其列表匹配

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

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

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

事实上,如果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}