0

Assume I have df below:

df = pd.DataFrame({
    'A': ['a', 'b'],
    'B': [1, 2],
    'C': [3, 4]
})

How can I turn this into a nested dict of the format:

{'a': {'B': 1, 'C': 2}, 'b': {'B': 3, 'C': 4}}

I've tried df.to_dict() which doesn't return the format I'm after.

Thanks!

2 Answers 2

3

Try set_index

df.set_index('A').to_dict('index')
Out[8]: {'a': {'B': 1, 'C': 3}, 'b': {'B': 2, 'C': 4}}
Sign up to request clarification or add additional context in comments.

1 Comment

This is like watching a gun fight in those old spaghetti westerns.
1

You can set A as index and use to_dict:

df.set_index('A').to_dict('i')
# {'a': {'B': 1, 'C': 3}, 'b': {'B': 2, 'C': 4}}

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.