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

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

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}

其他回答

使用字典理解(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))

再举一个例子。假设您有以下列表:

nums = [4,2,2,1,3]

您希望将其转换为dict,其中键是索引,值是列表中的元素。您可以使用以下代码行执行此操作:

{index:nums[index] for index in range(0,len(nums))}

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

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

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

在Python 2.7中,它类似于:

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

给他们拉链!

这段代码将使用列表理解为多个列表创建字典,这些列表具有可用于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,以使每个键与其列表匹配