0

i have this code so far

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)

but now i want to put the teamNames into the blank dictionary created, called teams, with a value of zero, but i dont know how.

Nick P
  • 17
  • 2
  • See http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python – lit Oct 06 '15 at 18:37

6 Answers6

1

As far as i understand, you want to add all the elements of teamNames list as the key of dictionary teams and assign the value 0 to each of them.

To do so, use a for loop to iterate through the list you already have and use the name as the key of the dictionary 1 by 1. Like below:

for name in teamNames:
    teams[name] =0
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
1

Outside of and after your existing for loop, add this line:

teams = {teamName:0 for teamName in teamNames}

This structure is called a dict comprehension.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

I would suggest:

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)
lskrinjar
  • 5,483
  • 7
  • 29
  • 54
0

you could loop over your array like you did

for name in teamNames:
      teams[name] = 0

that way you should fill the empty dictionary with the values of your array

Yeis Gallegos
  • 444
  • 2
  • 14
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))

Dictionaries already have lists for their keys. If you want the names in a particular order you can swap out the dict for an OrderedDict, but there's no reason to maintain the list of names independently of the teams dict.

Chad S.
  • 6,252
  • 15
  • 25
0

Interesting Python feature is defaultdict:

from collections import defaultdict

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

Check the documentation for more info.

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64