简体   繁体   中英

Python - to_dict() creates unwanted nested dictionary

Edit: the duplicate suggested was not able to resolve my issue as the indexed column is different from turning a normal df into a dict. Would appreciate it if the downvoter takes away the vote.

Very simple, I want to create a dictionary from a df, with the df indexes as keys, and a column called 'signal' as key-values. I've used the to_dict() method, however this produces a nested dictionary, rather than individual. Code:

df:

index             signal
james.mccallum    0
john.driscoe      1
...               ...
andrew.black      0

input:
score_dict = df.to_dict()

produces:
score_dict = {signal{james.mccallum: 0, john.driscoe: 1, ... andrew.black: 0}

desired:
score_dict = {james.mccallum: 0, john.driscoe: 1, ... andrew.black: 0}

I'm sure it's a simple fix, however have not been able to find anything related to what I want to do. Any help would be appreciated.

This is the intended behavior of to_dict (check this very good answer with inputs/outputs of the different possible args, followed with explanations on them).

In your case, just get all signal related values

>>> score_dict = df.to_dict()['signal']
{'james.mccallum': 0, 'john.driscoe': 1, 'andrew.black': 0}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM