1
teams = ['Argentina', 'Australia', 'Belgium', 'Brazil', 'Colombia', 'Costa Rica', 'Croatia', 'Denmark', 'Egypt', 'England', 'France', 'Germany', 'Iceland', 'Iran', 'Japan', 'Mexico', 'Morocco', 'Nigeria', 'Panama', 'Peru', 'Poland', 'Portugal', 'Russia', 'Saudi Arabia', 'Senegal', 'Serbia', 'South Korea', 'Spain', 'Sweden', 'Switzerland', 'Tunisia', 'Uruguay']

wins = {"wins" : 0}


combined_data = dict.fromkeys(teams, wins)

combined_data["Russia"]['wins'] +=1

print(combined_data["Belgium"]['wins'])

should print 0 but all 'wins' go up by 1 and printout 1

I also tried 'wins' with 32 keys, but not working.

Many thanks in advance.

2 Answers2

3

The wins dictionary is shared across all keys inside the combined_data dictionary.

To resolve this issue, use a dictionary comprehension instead:

combined_data = {team: {"wins" : 0} for team in teams}
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
1

Your code is not creating a new dictionary for each country, it's putting a reference to the exact same dictionary in each key's value. You can see this by running id() on two separate keys of the dataframe:

id(combined_data['Argentina'])   # 5077746752
id(combined_data['Sweden'])   # 5077746752

To do what you mean to do, you should use something like a dictionary expression:

combined_data = {team: {"wins" : 0} for team in teams}
baileythegreen
  • 1,126
  • 3
  • 16