Turn a single entry in a dictionary of dictionaries into a dataframe where keys are the columns

Viewed 2480

Given a dictionary such as:

records = {0:{'name':'John', 'salary':'5000'}, 1:{'name':'Bob', 'salary':'3500'}}

If I want to get and store (in csv) a dataframe such as:

name  salary
John   5000

By using records[0] as a way to access the dictionary inside, how would I do that?

I have tried:

df = pd.DataFrame(records[0], index=[0])

df= pd.DataFrame(list(records[0].values()), columns=list(records[0].keys()))

df= pd.DataFrame.from_dict(records[key], orient='columns')

But none of them worked as intended (2nd one gave me an error, 1st and last have just one column)

2 Answers

Use DataFrame.from_dict with orient='index':

df = pd.DataFrame.from_dict(records, orient='index')
print (df)
   name salary
0  John   5000
1   Bob   3500

EDIT - For first value of record pass to nested list:

df = pd.DataFrame([records[0]])
print (df)
   name salary
0  John   5000

You could use a combination of DataFrame.from_dict() and DataFrame.T :

records = {0:{'name':'John', 'salary':'5000'}, 1:{'name':'Bob', 'salary':'3500'}}
pd.DataFrame.from_dict(records).T

Output

+----+-------+--------+
|    | name  | salary |
+----+-------+--------+
| 0  | John  |   5000 |
| 1  | Bob   |   3500 |
+----+-------+--------+

EDIT To get just the first record

df[df.index==0]
+----+-------+--------+
|    | name  | salary |
+----+-------+--------+
| 0  | John  |   5000 |
+----+-------+--------+
Related