Convert Pandas dataframe to a dictionary with first column as key

Viewed 567

I have a Pandas Dataframe :

A  ||  B  ||  C
x1    x      [x,y]
x2    a      [b,c,d] 

and I am trying to make a dictionary to that looks like:

{x1: {B : x, c : [x,y]}, x2: {B: a, C:[b,c,d}}

I have tried the to_dict function but that changes the entire dataframe into a dictionary. I am kind of lost on how to iterate onto the first column and make it the key and the rest of the df a dictionary as the value of that key.

1 Answers

Try:

x = df.set_index("A").to_dict("index")
print(x)

Prints:

{'x1': {'B': 'x', 'C': ['x', 'y']}, 'x2': {'B': 'a', 'C': ['b', 'c', 'd']}}
Related