I think I know what I want. My output needs to have "teams" as dict keys, for each dict key there will be a nested dict, in each nested dict the key will be a players name, the values for each nested dict key will be a list of goals per game. I want to be able to find out who scored the highest amount of goals for each team eventually.
I don't know if a dataframe is better for this?
code to make nested dict - I didn't know how to do it
mydict = {"team" : {"players" : "goals_each_game"}}
team = list(range(1, 7))
print("team : ", team)
players = ["gk", "lb", "dl", "dr", "rb", "rw", "rm", "lm", "lw", "ls", "rs" ]
goals_each_game = list(range(1,7))
for d in team:
for k, v in mydict.items():
mydict["team"] = d
#mydict[v] = a nested dict of each player and their list of goals
for p in players:
teamlist = []
new_dict = {}
for k,v in new_dict.items():
new_dict[k] = p
new_dict[v] = goals_each_game
teamlist.append(new_dict)
mydict[v] = teamlist
for k,v in mydict.items():
print(k,v)
expected output
I want to know how to make this, and put any list of values inside the nested dicts instead of [1, 2, 3].
mydict = {"1": [{"gk":[1,2,3]}, {"lb":[1,2,3]}] ,"2": [{"gk":[1,2,3]}, {"lb":[1,2,3]}], "3": [{"gk":[1,2,3]}, {"lb":[1,2,3]}] ,"4": [{"gk":[1,2,3]}, {"lb":[1,2,3]}] }
for k,v in mydict.items():
print(k,v)
team : [1, 2, 3, 4, 5, 6]
1 [{'gk': [1, 2, 3]}, {'lb': [1, 2, 3]}]
2 [{'gk': [1, 2, 3]}, {'lb': [1, 2, 3]}]
3 [{'gk': [1, 2, 3]}, {'lb': [1, 2, 3]}]
4 [{'gk': [1, 2, 3]}, {'lb': [1, 2, 3]}]
Your outer-most dictionary is a dictionary whose keys are team indices and whose values are lists .
If your goal's to have each value be a dictionary of player initials to goals scored, you want teamlist
to be a {}
(and the call to teamlist.append
to be replaced with an assignment).
You could write this more idiomatically with a comprehension:
goals_per_game = list(range(1, 7))
mapping = {
d: {
p: goals_per_game
for p in players
}
for d in teams
}
There's a few caveats here. The first is that all teams share the same players; you may want to maintain a separate dictionary mapping teams to player initials.
The second is that—as written— goals_per_game
will be the same object across all players:
Assignment statements in Python do not copy objects, they create bindings between a target and an object
This means that mutating the list for one player will mutate it for all players in the above implementation. Consider:
mapping[1]['gk'].append(100)
print(mapping[2]['lb']) # Has 100!
To address this, you can either construct a new list for each player (ie by calling list o range
separately) or use copy
to construct a copy for each player.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.