0

I want to set two columns from my dataframe (EisDat_cvs) as dictionary key and value in python, and everything works fine using this code:

dict_EisukeID_HMDB = EisDat_cvs.set_index('Unnamed: 28')['Unnamed: 26'].to_dict()

However now I want to append two columns as values and one as key in the dictionary, and I tried to modify the previous one as:

dict_EisukeID_HMDB = EisDat_cvs.set_index('Unnamed: 28')['Unnamed: 26', 'Unnamed: 1'].to_dict()

But python throws me a key error...

EDIT

I have a dataframe EisDat_cvs, of which I am considering 3 columns (Unnamed: 28, Unnamed: 26, Unnamed: 1). And I want to get a dictionary that takes the values in column 28 as my keys, and values in column 26 and 1 as values in the dictionary. Something like this:

Unnamed: 28, Unnamed: 26, Unnamed: 1
bla.          1           90
cra           2           12
ta            3           12

and my output should look like

dict_EisukeID_HMDB = { 'bla': '1', '90'
                       'cra': '2', '12'
                       'ta':  '3', '12'}

1 Answer 1

1

You can try this:

dict(zip(
    EisDat_cvs['Unnamed: 28'],
    zip(EisDat_cvs['Unnamed: 26'], EisDat_cvs['Unnamed: 1'])
))

The issue you had was not with to_dict() but instead by passing the columns as a tuple, you are trying to access the dataframe through a hierarchal column structure, which if your dataframe does not have, will throw a KeyError.


Hierarchal columns example:

df = pd.DataFrame({
    ("A", "A0"): [10, 30, 50, 70],
    ("A", "A1"): [11, 31, 51, 71],
    ("B", "B0"): [20, 40, 60, 80],
    ("B", "B1"): [21, 41, 61, 81]
})

print(df["A", "A0"])

Output:

0    10
1    30
2    50
3    70
Name: (A, A0), dtype: int64
Sign up to request clarification or add additional context in comments.

2 Comments

Your code yeald a dictionary that takes as key the name of the 2 columns and as values the two pairs of columns, while the output should be a dictionary with the values in the first column as keys, and the values in second and third column as values of the dictionary
Could you edit your answer to provide an output you are expecting?

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.