【问题标题】:How to turn a list into a dictionary如何将列表变成字典
【发布时间】:2016-01-03 18:50:21
【问题描述】:
到目前为止我有这个代码
teamNames = []
teams = {}
while True:
print("Enter team name " + str(len(teamNames) + 1) + (" or press enter to stop."))
name = input()
if name == "":
break
teamNames = teamNames + [name]
print("The team names are ")
for name in teamNames:
print(" " + name)
但现在我想将 teamNames 放入创建的名为 teams 的空白字典中,其值为 0,但我不知道如何操作。
【问题讨论】:
标签:
python
list
for-loop
dictionary
while-loop
【解决方案1】:
据我了解,您希望将 teamNames 列表的所有元素添加为字典 teams 的键,并将值 0 分配给每个元素。
为此,请使用for 循环遍历您已经拥有的list,并将名称作为字典的key 1 比1。如下所示:
for name in teamNames:
teams[name] =0
【解决方案2】:
在现有的 for 循环之外和之后,添加以下行:
teams = {teamName:0 for teamName in teamNames}
这种结构称为dict理解。
【解决方案3】:
我建议:
teamNames = []
teams = {}
while True:
print("Enter team name " + str(len(teamNames) + 1) + (" or press enter to stop."))
name = input()
if name == "":
break
teamNames = teamNames + [name]
# add team to dictionary with item value set to 0
teams[name] = 0
print("The team names are ")
for name in teamNames:
print(" " + name)
【解决方案4】:
你可以像以前一样遍历你的数组
for name in teamNames:
teams[name] = 0
这样你应该用你的数组的值填充空字典
【解决方案5】:
prompt = "Enter the name for team {} or enter to finish: "
teams = {}
name = True #to start the iteration
while name:
name = input(prompt.format(len(teams)+1))
if name:
teams[name] = 0
print('The teams are:\n ' + '\n '.join(teams))
字典已经有它们的键的列表。如果您希望名称按特定顺序排列,您可以将字典替换为 OrderedDict,但没有理由独立于团队字典来维护名称列表。
【解决方案6】:
有趣的Python 功能是defaultdict:
from collections import defaultdict
teams = defaultdict(int)
for name in teamNames:
teams[name]
查看documentation 了解更多信息。