Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of dictionaries from a pandas DataFrame?

I am looking to try to set up a list with specific dictionaries. I would like the structure to be something similar to the following:

[{'label': 'Abdelnaby, Alaa', 'value': '76001'},
{'label': 'Abdul-Aziz, Zaid', 'value': '76002'},
{'label': 'Abdul-Jabbar, Kareem', 'value': '76003'}]

Currently, the data that I am pulling from is in a pandas dataframe. Example below...

PlayerID    Name     Current Player First Season    Last Season
76001   Abdelnaby, Alaa       0     1990            1994
76002   Abdul-Aziz, Zaid      0     1968            1977
76003   Abdul-Jabbar, Kareem  0     1969            1988
51      Abdul-Rauf, Mahmoud   0     1990            2000
1505    Abdul-Wahad, Tariq    0     1997            2003

Please let me know​ if this is sufficient. Thanks so much for the help!

like image 811
datam Avatar asked Mar 04 '23 03:03

datam


1 Answers

Select your columns, rename them and call to_dict with orient='records' to get a list of dicts,

(df.reindex(['Name', 'PlayerID'], axis=1)
   .set_axis(['label', 'value'], axis=1, inplace=False)
   .to_dict('r'))    

# [{'label': 'Abdelnaby, Alaa', 'value': 76001},
#  {'label': 'Abdul-Aziz, Zaid', 'value': 76002},
#  {'label': 'Abdul-Jabbar, Kareem', 'value': 76003},
#  {'label': 'Abdul-Rauf, Mahmoud', 'value': 51},
#  {'label': 'Abdul-Wahad, Tariq', 'value': 1505}]

You can output JSON by changing .to_dict('r') to .to_json(orient='records').


If performance matters, here is an optimised solution with list comprehension construction.

[dict(zip(('label', 'value'), r)) for r in df[['Name', 'PlayerID']].values]

# [{'label': 'Abdelnaby, Alaa', 'value': 76001},
#  {'label': 'Abdul-Aziz, Zaid', 'value': 76002},
#  {'label': 'Abdul-Jabbar, Kareem', 'value': 76003},
#  {'label': 'Abdul-Rauf, Mahmoud', 'value': 51},
#  {'label': 'Abdul-Wahad, Tariq', 'value': 1505}]
like image 85
cs95 Avatar answered Mar 06 '23 17:03

cs95