Skip to content Skip to sidebar Skip to footer

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

Solution 1:

You can use dict comprehension. Take a look below:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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

Post a Comment for "Python Iterators/ One Liner For Loop"