我可以使用列表理解语法来创建词典吗?
例如,通过迭代成对的键和值:
d = {... for k, v in zip(keys, values)}
我可以使用列表理解语法来创建词典吗?
例如,通过迭代成对的键和值:
d = {... for k, v in zip(keys, values)}
当前回答
这段代码将使用列表理解为多个列表创建字典,这些列表具有可用于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,以使每个键与其列表匹配
其他回答
您可以为每对创建一个新的dict,并将其与上一个dict合并:
reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})
显然,这种方法需要functools的reduce。
这种方法使用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,请执行以下操作:
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])
是的,这是可能的。在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}
事实上,如果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}