Daniel Lee
Daniel Lee

Reputation: 8011

Python iterators/ one liner for loop

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.

Upvotes: 0

Views: 370

Answers (4)

Skycc
Skycc

Reputation: 3555

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'}

Upvotes: 1

gipsy
gipsy

Reputation: 3859

TEAMS = [u'New Zealand', u'USA']    
dict(zip(TEAMS, ['Rugby'] * 2))

Upvotes: 0

pt12lol
pt12lol

Reputation: 2441

You can use dict comprehension. Take a look below:

TEAMS = [u'New Zealand', u'USA']
d = {team: 'Rugby' for team in TEAMS}

Upvotes: 3

vsr
vsr

Reputation: 1127

for team in TEAMS:
    dict.update({team: u'Rugby'})

Upvotes: 0

Related Questions