Reading values ​​from a CSV file in a list dictionary

I have a CSV file with one column with a name Triggerand two other columns called void1and void2.

The data is as follows:

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 started using the following code:

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

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

What works. However, when I try:

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

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

This does not work. Any ideas how I can get the conclusion I'm looking for?

+4
source share
3 answers

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

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

To:

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

It is also assumed that your CSV file looks like this:

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

instead of this:

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

, , . String .

+2

, row :

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

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

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

Then you call tolistbecause it row[['void1', 'void2']]returns a Series object instead of a regular list.

0
source

Source: https://habr.com/ru/post/1686047/


All Articles