Using a dict comprehension transform dataframe columns into dict

Question:

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.

Asked By: tucomax

||

Answers:

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()}
Answered By: bn_ln