Home > Software engineering >  How to edit a value of a dictionary?
How to edit a value of a dictionary?

Time:04-21

I have a dataframe of three integer columns. I want to create a dictionary which uses two first columns as a key, and the third column as a value.

To do so I convert two first columns into an index and apply dataframe.to_dict('index').

The problem: my dict looks like this: {(111,222):{'colname3': 0.1}.

The question: how to edit the column name out of the dict's values to transform the dict into: {(111,222): 0.1}?

My dataframe looks like this:

index colname1 colname2 colname3
0     111      222      0.1
1     111      333      0.2
2     111      444      0.3
3     222      111      0.4
4     222      333      0.5

CodePudding user response:

Set the index to be colname1 & 2, select colname3 and convert to dict:

df.set_index(['colname1', 'colname2'])['colname3'].to_dict()

Output:

{(111, 222): 0.1,
 (111, 333): 0.2,
 (111, 444): 0.3,
 (222, 111): 0.4,
 (222, 333): 0.5}
  • Related