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.

1
  • 2
    If the value is an immutable object then you can simply do: dict.fromkeys(TEAMS, u'Rugby'). Commented Nov 9, 2016 at 11:06

4 Answers 4

3

You can use dict comprehension. Take a look below:

TEAMS = [u'New Zealand', u'USA']
d = {team: 'Rugby' for team in TEAMS}
2
  • you might want to rename your variable to a non built-in type Commented Nov 9, 2016 at 11:14
  • done. just provided the same name as the author had.
    – pt12lol
    Commented Nov 9, 2016 at 11:15
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'}
0
for team in TEAMS:
    dict.update({team: u'Rugby'})
0
TEAMS = [u'New Zealand', u'USA']    
dict(zip(TEAMS, ['Rugby'] * 2))

Not the answer you're looking for? Browse other questions tagged or ask your own question.