Reputation: 664
My current df:
header1 header2
Siam Thailand
Indonesie Indonesia
Arabie Yemen
Ceylon Sri Lanka
So the headers of my df are 'header1' and 'header2'. The values are everything under these two headers.
I would like to transform this df into a flat dictionary, where the dictionary keys are the values of header1 and the dictionary values are the values of header2, like so:
Desired output:
{'Siam': 'Thailand', 'Indonesië': 'Indonesia', 'Arabië': 'Yemen', 'Ceylon': 'Sri Lanka'}
Current output:
{'header2':{'Siam': 'Thailand', 'Indonesie': 'Indonesia', 'Arabie': 'Yemen', 'Ceylon': 'Sri Lanka'}}
My code:
df.to_dict()
Upvotes: 3
Views: 1615
Reputation: 150785
This is just:
{a:b for a,b in zip(df['header1'], df['header2'])}
or if you insist on pandas
solution:
df.set_index('header1')['header2'].to_dict()
Output:
{'Siam': 'Thailand',
'Indonesie': 'Indonesia',
'Arabie': 'Yemen',
'Ceylon': 'Sri Lanka'}
Upvotes: 5