Python 如何将列表转换为词典
到目前为止我有这个代码Python 如何将列表转换为词典,python,list,for-loop,dictionary,while-loop,Python,List,For Loop,Dictionary,While Loop,到目前为止我有这个代码 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 n
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)
但是现在我想把团队名称放在空白字典中,称为团队,值为零,但我不知道如何。
< P>我建议: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)
您可以像以前一样在阵列上循环
for name in teamNames:
teams[name] = 0
这样,您应该用数组的值填充空字典。据我所知,您希望将
teamNames
列表的所有元素添加为dictionaryteams
的键,并将值0
分配给每个元素
要执行此操作,请使用for
循环遍历已有的列表
,并使用名称作为字典的键
。如下图所示:
for name in teamNames:
teams[name] =0
字典已经有了它们的关键字列表。如果您希望名称按特定顺序排列,您可以将dict换成OrderedDict,但没有理由独立于团队dict维护名称列表。在现有
for
循环之外和之后,添加以下行:
teams = {teamName:0 for teamName in teamNames}
这种结构称为dict理解。有趣的
Python
功能是defaultdict
:
from collections import defaultdict
teams = defaultdict(int)
for name in teamNames:
teams[name]
查看以了解更多信息。请参阅
from collections import defaultdict
teams = defaultdict(int)
for name in teamNames:
teams[name]