Reputation: 8011
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
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
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