Unpack a python dictionary and save as variables

Advertisements

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!

>Solution :

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.

Leave a ReplyCancel reply