Daniel Lee Daniel Lee -4 years ago 144
Python Question

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.

Answer Source

You can use dict comprehension. Take a look below:

TEAMS = [u'New Zealand', u'USA']
d = {team: 'Rugby' for team in TEAMS}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download