0

I have a dataframe with 2 columns name and age

I want to make a list of dictionaries containing their value of name and age which is like this

list = [{'a':'14'}, {'b':'21'}, {'c':'12'}]

I've tried using list = [{i:j} for i,j in df['name'],df['age']] but apparently it cannot loop from 2 for in. How can I loop the list of dictionaries?

EDIT

I have completed it with list = [{i:j} for i,j in zip(df['name'],df['age'])]

Thank you for the answers!

Kenny
  • 85
  • 9
  • 1
    Use `zip`, i.e. `[{i:j} for i,j in zip(df['name'],df['age'])] `. Also, don't use `list` as a variable name. It will mask the builtin `list` which you really don't want to do. – Tom Karzes Sep 10 '20 at 06:33
  • HI thank you for answering, yes the ```zip``` works fine. Thank you @TomKarzes – Kenny Sep 10 '20 at 06:37
  • @Kenny Aside from that, why do you want to make a list of one-element dictionaries? It is not normally a convenient way to organise your data. The equivalent dictionary `{i:j for i,j in zip(df['name'],df['age'])}` would almost certainly be much more useful. – alani Sep 10 '20 at 06:38
  • 1
    even simple like this `dict(zip(df['name'],df['age']))` – deadshot Sep 10 '20 at 06:40
  • Good point thanks @deadshot – alani Sep 10 '20 at 06:40
  • I am currently using dash in my project and I want to make a list data for other usage :) @alani – Kenny Sep 10 '20 at 06:41
  • Use this df.to_dict('records') – Deepak Tripathi Sep 10 '20 at 06:47
  • @deadshot That produces a different result. OP wants a list of single-element dicts, not a single flattened dict. – Tom Karzes Sep 10 '20 at 06:53

2 Answers2

2

I don't know if it works but try this

list = [{i:j} for i,j in zip(df['name'],df['age'])]
1

you should be able to do that with zip. Try: [{i:j} for i,j in zip(df['name'],df['age'])]

drops
  • 1,524
  • 1
  • 11
  • 20