2015-10-06 139 views
0

我有这样的代码到目前为止如何把一个列表转换成字典

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到所创建的空白字典,叫团队,具有零值,但我不知识。

+0

请参阅http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python – lit

回答

1

由于价值观的空字典据我所知,你想添加teamNames列表的所有元素作为字典teams的键,并将值0分配给每个其中。

要做到这一点,使用for遍历list迭代你已经有了和1使用的名称为字典1的key象下面这样:

for name in teamNames: 
    teams[name] =0 
0

我建议:

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) 
0

你可以循环在你的阵列像你这样

for name in teamNames: 
     teams[name] = 0 

这样你应该填写您阵列

0

你最好了解Python中词典的基本语法。这里有一些很好的书入手:Free Python Books

你的代码是:

teams[name] = 0 
0
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的字典,但是没有理由保持独立于团队字典的名字列表。

1

之外,并且现有的for循环后,加入这一行:

teams = {teamName:0 for teamName in teamNames} 

这种结构被称为字典理解

0

有趣Python特点是defaultdict

from collections import defaultdict 

teams = defaultdict(int) 
for name in teamNames: 
    teams[name] 

检查documentation以获得更多信息。