1

I have a dictionary as such:

{1:{'name':'john', 'age':26,'salary':50000},11:{'name':'peter', 'age':34, 'salary':70000},14:{'name': 'david', 'age': 21, 'salary': 15000}}

I would like to convert it to a dataframe like this:

name  age  salary
john  26   50000
peter 34   70000
david 21   15000

4 Answers 4

2

Use from_dict with orient='index':

pd.DataFrame.from_dict(d, orient='index')

     name  age  salary
1    john   26   50000
11  peter   34   70000
14  david   21   15000
2
  • Can I create a column name for the indexes(1,11,14) in the above dataframe and create a seperate serialized index Nov 19, 2018 at 1:50
  • 1
    Yes, just call reset_index on the result Nov 19, 2018 at 2:46
2

You can load the dictionary directly into a dataframe and then transpose it:

d = {1:{'name':'john', 'age':26,'salary':50000},11:{'name':'peter', 'age':34, 'salary':70000},14:{'name': 'david', 'age': 21, 'salary': 15000}}

df = pd.DataFrame(d).T

   age   name salary
1   26   john  50000
11  34  peter  70000
14  21  david  15000
1

Construct the dataframe out of your dict's values.

>>> d = {1:{'name':'john', 'age':26,'salary':50000},11:{'name':'peter', 'age':34, 'salary':70000},14:{'name': 'david', 'age': 21, 'salary': 15000}}
>>> pd.DataFrame(list(d.values()))
   age   name  salary
0   26   john   50000
1   34  peter   70000
2   21  david   15000

With rearranged columns:

>>> pd.DataFrame(list(d.values()), columns=['name', 'age', 'salary'])
    name  age  salary
0   john   26   50000
1  peter   34   70000
2  david   21   15000
0
0

Do this:

pd.DataFrame(list(d.values()))

If you're using Python2, you can directly call pd.DataFrame with p.values() like this:

pd.DataFrame(d.values())

This is because dictionary values no longer returns a list in python3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.