Reputation: 193
I'm trying to create a nested dictionary / list json-like structure in python, however I'm not sure if my solution is optimal. Esseeantially I'm building list of lists for teams, which will then house their players, player ids, etc.
Below is is my code. Ideally, if i wanted to find players on team alpha, i'd type
team_info['Alpha']['players']
however i have to refer to the location of 'players' in order to pull it, for example:
team_info['Alpha'][0]['players']
players_list = [['A','B','C'],['D','E','F'],['G','H','I']]
id_list = [[1,2,3],[4,5,6],[7,8,9]]
teams = ['Alpha', 'Bravo', 'Charlie']
team_info = {}
for a,b in enumerate(teams):
players = {}
ids = {}
players['players']=players_list[a]
ids['ids']=id_list[a]
team_info[b]=[players,ids]
This doesn't work
team_info['Alpha']['players']
I have to reference by position.
team_info['Alpha'][0]['players']
Upvotes: 0
Views: 61
Reputation: 315
I'm not exactly sure what you are trying to accomplish, but I guess you would get further by using actual nested dictionaries - take a look at this tutorial on them.
Instantiation:
nested_dict = {
'dictA': {
'key_1': 'value_1',
'key_2': 'value_2'
},
'dictB': {
'key_a': 'value_b',
'key_n': 'value_n'
}
}
Access:
value = nested_dict['dictA']['name']
Upvotes: 0
Reputation: 10799
player_lists = [
["A", "B", "C"],
["D", "E", "F"],
["G", "H", "I"]
]
id_lists = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
teams = [
"Alpha",
"Bravo",
"Charlie"
]
team_info = {}
for team, player_list, id_list in zip(teams, player_lists, id_lists):
team_info[team] = {
"players": player_list,
"ids": id_list
}
Upvotes: 0
Reputation: 8273
You do not need two dicts you just need one with two keys
for a,b in enumerate(teams):
players_info={}
players_info['players']=players_list[a]
players_info['ids']=id_list[a]
team_info[b]=players_info
Output of team_info['Alpha']['players']
: ['A', 'B', 'C']
The final dict will look like
{'Alpha': {'players': ['A', 'B', 'C'], 'ids': [1, 2, 3]},
'Bravo': {'players': ['D', 'E', 'F'], 'ids': [4, 5, 6]},
'Charlie': {'players': ['G', 'H', 'I'], 'ids': [7, 8, 9]}}
Upvotes: 2