gftsp
gftsp

Reputation: 13

Store list of dictionaries as a DataFrame

Suppose I have List of dictionaries as

 l = [{'car':'good'},
      {'mileage':'high'},
      {'interior':'stylish'},
      {'car':'bad'},
      {'engine':'powerful'},
      {'safety':'low'}]

Basically these are noun-adjective pairs.

  1. How can I visualize whats the most associated list of adjective to lets say car here.
  2. How to convert this to Data frame? , I have tried pd.Dataframe(l) , but here the key is not the column name so gets little bit tricky here.

Any help would be appreciated.

Sample output

Upvotes: 0

Views: 62

Answers (2)

David
David

Reputation: 1202

Given that you want this to be done column-wise, then you have to re-structure your list of dictionaries. You need to have one dictionary to represent one row. Therefore, your example list should be (I added a second row for better explainability):

 l = [
     {'car':'good','mileage':'high','interior':'stylish','car':'bad','engine':'powerful','safety':'low'}, # row 1
     {'car':'bad','mileage':'low','interior':'old','car':'bad','engine':'powerful','safety':'low'} # row 2
 ]

At this point, all you have to do is call pd.DataFrame(l).

EDIT: Based on your comments, I think you need to convert the dictionary to a list to get your desired result. Here is a quick way (I'm sure it can be much more efficient):

l = [{'car':'good'},
      {'mileage':'high'},
      {'interior':'stylish'},
      {'car':'bad'},
      {'engine':'powerful'},
      {'safety':'low'}]

new_list = []
for item in l:
    for key, value in item.items():
        temp = [key,value]
        new_list.append(temp)

df = pd.DataFrame(new_list, columns=['Noun', 'Adjective'])

Upvotes: 2

manu190466
manu190466

Reputation: 1603

You can construct your DataFrame by giving a list of tuples. To get tuples from a dict use the method items(). Construct the list of tuples with a list comprehension by taking the first tuple of each items.

import pandas as pd
df=pd.DataFrame(data=[d.items()[0] for d in l],columns=['A','B'])
print df

Gives :

          A         B
0       car      good
1   mileage      high
2  interior   stylish
3       car       bad
4    engine  powerful
5    safety       low

Upvotes: 0

Related Questions