Python 使用zip构建dict
我有一份名单:Python 使用zip构建dict,python,Python,我有一份名单: ['john smith', 'sally jones', 'bob jones'] 我想以以下格式构建dict: {'john smith': [], 'sally jones': [], 'bob jones': []} 这就是我尝试使用zip时发生的情况 zip((all_crew_names, [[] for item in all_crew_names])) [(['john smith', 'sally jones', 'bob jones'],), ([[],
['john smith', 'sally jones', 'bob jones']
我想以以下格式构建dict:
{'john smith': [], 'sally jones': [], 'bob jones': []}
这就是我尝试使用zip时发生的情况
zip((all_crew_names, [[] for item in all_crew_names]))
[(['john smith', 'sally jones', 'bob jones'],), ([[], [], []],)]
我在这里做错了什么,我该如何正确地把拉链拉上?你不需要拉链
在较早版本的Python中,没有这样的字典理解,因此可以使用以下代码:
dict((name, []) for name in all_crew_names)
你不需要拉链
在较早版本的Python中,没有这样的字典理解,因此可以使用以下代码:
dict((name, []) for name in all_crew_names)
这里最简单的解决方案是词典理解:
names = ['john smith', 'sally jones', 'bob jones']
d = {name: [] for name in names}
请注意,使用dict.fromkeysnames,[]可能很有诱惑力,但这会导致所有键都使用相同的列表。这里最简单的解决方案是字典理解:
names = ['john smith', 'sally jones', 'bob jones']
d = {name: [] for name in names}
请注意,使用dict.fromkeysnames,[]可能很有诱惑力,但这会导致所有键都使用相同的列表。您需要实际使用dict构造函数,并且括号太多:
dict(zip(all_crew_names, [[] for item in all_crew_names])
您需要实际使用dict构造函数,并且括号太多:
dict(zip(all_crew_names, [[] for item in all_crew_names])
对于没有字典理解的老蟒蛇:dictname,[]对于没有字典理解的老蟒蛇:dictname,[]对于没有字典理解的老蟒蛇:dictname,[]对于没有字典理解的老蟒蛇,[]对于没有字典理解的老蟒蛇,+1对于实际回答问题的“我在做什么不正确”部分+1对于实际回答问题的“我在做什么不正确”部分