-1

I have a dataframe with a column that contains concatenated lists.

| A        | B                  |
| -------- | --------------     |
| Cow      | ["Sheep","Pig","Bear"]            
| Monkey   | ["Frog","Toad","Bird"]   

How do I convert this to a dictionary where Column A is the key and Column B are the values?

Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
BB123
  • 33
  • 1
  • 6
  • 1
    may be this would help? https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html – Prashant Ghimire Feb 16 '23 at 04:17
  • Does this answer your question? [Convert a Pandas DataFrame to a dictionary](https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary) – Blue Robin Feb 16 '23 at 04:18

3 Answers3

1

You can use

dictionary = df.set_index('A')['B'].to_dict()

The result

>>> dictionary
{'cow': ['Sheep', 'Pig', 'Bear'], 'Monkey': ['Frog', 'Toad', 'Bird']}
biyazelnut
  • 256
  • 7
0

This solution is flexible, but I wouldn't recommend it on large datasets.

import pandas as pd

data = [['cow', ["Sheep","Pig","Bear"]], ['Monkey', ["Frog","Toad","Bird"]]]

df = pd.DataFrame(data, columns=['A', 'B'])

def df_toDict(obj, my_dict):
    my_dict[obj['A']] = obj['B']

my_dict = {}
df.T.apply(lambda _ : df_toDict(_, my_dict))

print(my_dict)

By using T you transpose the DataFrame since pandas is naturally oriented to columns. Use the apply function to intirate over the columns (rows.T) and apply a function passing in the dictionary you want to populate.

Klarich
  • 1
  • 1
0

You can use:

>>> df.set_index('A')['B'].to_dict()

{'Cow': ['Sheep', 'Pig', 'Bear'],
 'Monkey': ['Frog', 'Toad', 'Bird']}
Corralien
  • 109,409
  • 8
  • 28
  • 52