Home > Back-end >  Unpack a python dictionary and save as variables
Unpack a python dictionary and save as variables

Time:04-02

I have the following string extracted from a pandas column (its an sport example):

unpack ="{'TB': [['Brady', 'Godwin'], ['2023-RD1', '2023-RD4']], 'KC': [['Mahomes'], ['2023-RD2']]}"

To upack the string i use the following:

from ast import literal_eval
t_dict = literal_eval(unpack)
print(t_dict)

which gives me:

{'TB': [['Brady', 'Godwin'], ['2023-RD1', '2023-RD4']], 'KC': [['Mahomes'], ['2023-RD2']]}

I am now trying to extract all of these keys / values to variables/lists. My expected output is:

 team1 = 'TB'
 team2 = 'KC'                
 team1_trades_players = ['Brady', 'Godwin']
 team1_trades_picks = ['2023-RD1', '2023-RD4']
 team2_trades_players = ['Mahomes']
 team2_trades_picks = ['2023-RD2]

I have tried the following but I am unsure how to send the first iteration to team1 and 2nd iteration to team2:

#extracting team for each pick
for t in t_dict:
    print(t)

Gives me:

TB
KC

And then for the values i can correctly print them but unsure how to send back to the lists:

#extracting lists for each key:
for traded in t_dict.values():
    #extracting the players traded for each team
    for players in traded[0]:
        print(players)
    #extracting picks for each team
    for picks in traded[1]:
        print(picks)

Produces:

Brady
Godwin
2023-RD1
2023-RD4
Mahomes
2023-RD2

I think i am close but missing the final step of sending back to their variables/lists. Any help would be greatly appreciated! Thanks!

CodePudding user response:

If the number of teams is known beforehand it is pretty simple:

team1, team2 = t_dict.keys()
team1_trades_players, team1_trades_picks = t_dict[team1]
team2_trades_players, team2_trades_picks = t_dict[team2]

If the number of teams is not known beforehand, I would recommend to just use t_dict.

CodePudding user response:

I would recommend to put everything in a nested dict which you then can access easiely:

t_dict = {'TB': [['Brady', 'Godwin'], ['2023-RD1', '2023-RD4']], 'KC': [['Mahomes'], ['2023-RD2']]}

t_nested = {k:{"players": v[0], "picks": v[1]} for k,v in t_dict.items()}

team1 = list(t_nested.keys())[0]
team2 = list(t_nested.keys())[1]     
team1_trades_players = t_nested[team1]['players']
team1_trades_picks = t_nested[team1]['picks']
team2_trades_players = t_nested[team2]['players']
team2_trades_picks = t_nested[team2]['picks']

But probably for most use cases it would be better to just keep it in that nested dict structure and use it directly instead of creating all these variables which make everything less dynamic.

  • Related