Read values from a .csv file into a list dictionary

Viewed 595

I have a .csv file with one column called Trigger and two other columns called void1 and void2.

The data looks like this:

Trigger;void1;void
good;not good;not to good;

I would like to use this data to create a dictionary that looks like this:

dictionary ={"good":["not good", "not to good"]}

I used the following code to start:

df = pd.read_csv('dictionary.csv', sep =";")

for index, row in df.iterrows():
    dictionary[row['trigger']] = row['void1']

Which works. However when I try:

df = pd.read_csv('dictionary.csv', sep =";")

for index, row in df.iterrows():
    dictionary[row['trigger']] = row['void1', 'void2']

It doesn't work. Any ideas how I can get the output I am looking for?

3 Answers

Assuming Numpy works like standard Python Lists, you need to change this line:

    dictionary[row['trigger']] = row['void1', 'void2']

To:

    dictionary[row['trigger']] = [row['void1'], row['void2']]

Also assuming that your CSV File actually looks like this:

    Trigger;void1;void2
    good;not good;not to good;

instead of this:

    Trigger;void1;void
    good;not good;not to good;

Also notice that your first example does not save the entries as you wanted it to. You are storing a String as dictionary value instead of an array.

Please access only one column from row at a time:

for index,row in df.iterrows():
    dictionary[row['trigger']] = [row['void1'], row['void2']]

In pandas you can have a list inside the index operator ([]) in order to select the columns you want. You were almost there with the row['void1', 'void2'] syntax, you just need a second group of brackets:

dictionary[row['trigger']] = row[['void1', 'void2']].tolist()

You then call tolist because row[['void1', 'void2']] will return a Series object instead of a plain list.

Related