Imsa
Imsa

Reputation: 1125

Pandas Columns to Flattened Dictionary (instead of list of dictionaries)

I have a DF that looks like this. df = pd.DataFrame({'ID': {0: 1, 1: 2, 2: 3}, 'Value': {0: 'a', 1: 'b', 2: np.nan}})

ID Value
0 1 a
1 2 b
2 3 c

I'd like to create a dictionary out of it. So if I run df.to_dict('records'), it gives me

[{'Visual_ID': 1, 'Customer': 'a'},
 {'Visual_ID': 2, 'Customer': 'b'},
 {'Visual_ID': 3, 'Customer': 'c'}]

​However, what I want is the following.

{
    1: 'a',
    2: 'b',
    3: 'c'
}

All of the rows in the DF or unique, so it shouldn't run into same key names issue.

Upvotes: 0

Views: 29

Answers (1)

BENY
BENY

Reputation: 323316

Try with

d = dict(zip(df.ID, df.Value))

Upvotes: 2

Related Questions