user17704364
user17704364

Reputation:

writing a dict comprehension in loops

Can anyone help me make this dict comprehension into loop and such so I can understand it better. We have not done dict comprehension in school yet, and its all a bit confusing. Thanks for the help.

team2scores = {team: [input_dict.get(member) for member in members] for team, members in team_members.items()}

print(team2scores)

these are the dictionaries in case anyone need them:

team_members = {'TeamA': ['Alice', 'Bob', 'Gertrude'], 'TeamB': ['Carol', 'Dave'], 'TeamC': ['Edith', 'Frank', 'Helen']}

input_dict = {'Alice': 1, 'Bob': 4, 'Carol': 5, 'Dave': 8, 'Edith': 6, 'Frank': 2, 'Gertrude': 9, 'Helen': 7}

Upvotes: 0

Views: 42

Answers (1)

chepner
chepner

Reputation: 530940

The conversion is fairly simple:

# team2scores = {team: [input_dict.get(member) for member in members] for team, members in team_members.items()}

team2scores = {}
for team, members in team_members.items():
    team2scores[team] = [input_dict.get(member) for member in members]

The generator becomes the start of the for loop, and the expression k: v becomes an assignment team2scores[k] = v.

Because you are making individual assignments to specific keys, you need to start with an empty dict that can serve as the target for the assignments.

Upvotes: 2

Related Questions