0

This may be obvious, but I'm stuck as to whether I can use an iterator/one liner to achieve the following:

TEAMS = [u'New Zealand', u'USA']
dict = {}

How can I write:

for team in TEAMS:
    dict[team] = u'Rugby'

as an iterator, for example:

 (dict[team] = u'Rugby' for team in TEAMS) # Or perhaps
 [dict[team] for team in TEAMS] = u'Rugby

Can it be done, where do the parentheses need to be placed?

Required output:

dict = {u'New Zealand': u'Rugby', u'USA': u'Rugby'}

I know there are lots of questions related to iterators in python, so I apologize if this has an answer, I have tried looking and couldn't find a good answer to this particular issue.

Daniel Lee
  • 7,189
  • 2
  • 26
  • 44

4 Answers4

3

You can use dict comprehension. Take a look below:

TEAMS = [u'New Zealand', u'USA']
d = {team: 'Rugby' for team in TEAMS}
pt12lol
  • 2,332
  • 1
  • 22
  • 48
1

use dict fromkeys method. Also, not recommended to use keyword dict as var name, change to d instead

TEAMS = [u'New Zealand', u'USA']
d = {}.fromkeys(TEAMS, u'Rugby')
# d = {u'New Zealand': u'Rugby', u'USA': u'Rugby'}
Skycc
  • 3,496
  • 1
  • 12
  • 18
0
for team in TEAMS:
    dict.update({team: u'Rugby'})
vsr
  • 1,025
  • 9
  • 17
0
TEAMS = [u'New Zealand', u'USA']    
dict(zip(TEAMS, ['Rugby'] * 2))
gipsy
  • 3,859
  • 1
  • 13
  • 21