Python词典理解中的多重赋值

Python词典理解中的多重赋值,python,dictionary,python-3.x,list-comprehension,Python,Dictionary,Python 3.x,List Comprehension,假设我有一张清单 demo = [['Adam', 'Chicago', 'Male', 'Bears'], ['Brandon', 'Miami', 'Male', 'Dolphins']] 我想列出一个字典列表,使用的理解如下 [{'Adam':'Chicago', 'Gender':'Male', 'Location':'Chicago', 'Team':'Bears'}, {'Brandon':'Miami', 'Gender':'Male', 'Location':'Miami',

假设我有一张清单

demo  = [['Adam', 'Chicago', 'Male', 'Bears'], ['Brandon', 'Miami', 'Male', 'Dolphins']]
我想列出一个字典列表,使用的理解如下

[{'Adam':'Chicago', 'Gender':'Male', 'Location':'Chicago', 'Team':'Bears'},
{'Brandon':'Miami', 'Gender':'Male', 'Location':'Miami', 'Team':'Dolphins'} }
分配两个起始值很容易得到如下结果

{ s[0]:s[1] for s in demo} 
但是,在这种理解中,有没有一种合法的方式来分配多个可能看起来像

{ s[0]:s[1],'Gender':s[2], 'Team':s[3] for s in demo} 

这是一个如此具体的问题,而且我不知道搜索的术语,所以我很难找到它,上面的例子给了我一个语法错误。

词典理解构建单个词典,而不是词典列表。你说你想列一个字典列表,所以用列表理解来做

modified_demo = [{s[0]:s[1],'Gender':s[2], 'Team':s[3]} for s in demo]

您的需求看起来很奇怪,您确定您没有尝试以逻辑方式命名字段(这更有意义):


您可以使用zip将每个条目转换为键值对列表:

dicts= [dict(zip(('Name','Gender','Location', 'Team'), data) for data in demo]
您不需要“名称”标签,而是希望将该名称用作复制位置的标签。所以,现在你需要修正一下口述:

for d in dicts:
    d[d['Name']] = d['Location']
    del d['Name'] # or not, if you can tolerate the extra key
或者,您可以通过一个步骤完成此操作:

dicts = [{name:location,'Location':location,'Gender':gender, 'Team':team} for name,location,gender,team in demo]

@JonClements好吧,这和你的解决方案一样,只是多了一步。序列分配会更好。
dicts = [{name:location,'Location':location,'Gender':gender, 'Team':team} for name,location,gender,team in demo]