Home > Net >  Using a dict comprehension transform dataframe columns into dict
Using a dict comprehension transform dataframe columns into dict

Time:10-25

I've got this DataFrame:

country city
Argentina Buenos Aires
Bangladesh Dhaka
Brasil Sao Paulo, Rio de Janeiro

I would like to get a dictionary using a dict comprehension:

{Argentina:[Buenos Aires], Bangladesh:[Dhaka], Brasil:[Sao Paulo, Rio de Janeiro]}

x = {k : column.values() for k, column in df.to_dict().items() }

It is an exercise and I can only use dict comprehension. I was trying to do the above code, but the result is not what I'm looking for.

Any help will be appreciate.

CodePudding user response:

Here's a trick to split and clean the values lists.

new_dict = {row['country']:list(map(lambda x: x.strip(), row['city'].split(','))) for _, row in df.iterrows()}
  • Related