1

I want to transfer a nested dic to a dataframe. (The dataframe should not be nested, only the highest layer from the dic should be converted to a dataframe).

dic =  {'Key1': 
                  {'Key1_1': [],
                   'Key1_2': 
                            {'Key1_2_1':
                                    {'Key1_2_1_1': 'value1_2_1_1'},
                              'Key1_2_2': ['listelement1value1_2_2']}},
        'Key2': 'value2', 
        'Key3': 'value3', 
        'Key4': 'value4'}

with

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

i get:

+----+--------+--------+--------+--------+
|    |   Key1 | Key2   | Key3   | Key4   |
|----+--------+--------+--------+--------|
|  0 |    nan | value2 | value3 | value4 |
+----+--------+--------+--------+--------+

with

series = pd.Series(dic)
df = series.to_frame().T

+----+----------------------------------------------------------------------------------------------------------------+--------+--------+--------+
|    | Key1                                                                                                           | Key2   | Key3   | Key4   |
|----+----------------------------------------------------------------------------------------------------------------+--------+--------+--------|
|  0 | {'Key1_1': [], 'Key1_2': {'Key1_2_1': {'Key1_2_1_1': 'value1_2_1_1'}, 'Key1_2_2': ['listelement1value1_2_2']}} | value2 | value3 | value4 |
+----+----------------------------------------------------------------------------------------------------------------+--------+--------+--------+

and the second result is that what i want. Is there a better way to get the second result without using a series first ?

1
  • 2
    I don't think there's anything wrong with your approach, looks fine! Commented Jun 12, 2018 at 5:31

1 Answer 1

1

Use:

df = pd.DataFrame([dic])
print (df)
                                                Key1    Key2    Key3    Key4
0  {'Key1_1': [], 'Key1_2': {'Key1_2_1': {'Key1_2...  value2  value3  value4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.