Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列表转换为词典_Python_List_For Loop_Dictionary_While Loop - Fatal编程技术网

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
列表的所有元素添加为dictionary
teams
的键,并将值
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]