0

I have a .csv file containing tweets and their sentiment polarity. Using DictReader, I see each row in the file in the format:

Sentiment: '0', SentimentText: 'xyz'

Now I want to add each row of the file to a pre-existing dictionary such that the structure of the dictionary at the end is:

{{Sentiment: '0', SentimentText: 'xyz'},
 {Sentiment: '1', SentimentText: 'abc'}...#so on until eof}

Is there any way that this is possible?

EDIT: So far, this is what I have achieved. This basically makes a list of dictionaries:

dataset = []
with open('SentimentAnalysisDataset.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    count = 1
    for row in reader:
        data = [{'Text': row['SentimentText'], 'Polarity': row['Sentiment']}]
        tuple = {str(count): data}
        count = count + 1
        dataset.append(tuple)

1 Answers1

1

This:

{{Sentiment: '0', SentimentText: 'xyz'},
 {Sentiment: '1', SentimentText: 'abc'}...#so on until eof}

Is not a valid dictionary structure. If you wish to use a list, this will work:

[{Sentiment: '0', SentimentText: 'xyz'},
 {Sentiment: '1', SentimentText: 'abc'}...#so on until eof]

Otherwise, you're probably looking for a structure like this:

{'0': 'xyz',
 '1': 'abc',
 ...}

In order to do that, you should update the existing dictionary like so:

existing_dict = {'0': 'xyz',
                 '1': 'abc'}

existing_dict[row['Sentiment']] = row['SentimentText']

# OR
new_dict = {row['Sentiment']: row['SentimentText'],
            ... # For all sentiments in file
            }
existing_dict.update(new_dict)
Bharel
  • 23,672
  • 5
  • 40
  • 80