Home > Software engineering >  How to read csv to dictionary with multiple values?
How to read csv to dictionary with multiple values?

Time:11-29

I want to read data like below into like this:

{
  'a' : ['row1,'row2','row3'], 
  'b' : ['row1,'row2','row3']
}
columns A columns B
a row1
a row2
a row3
b row 1
b row 2
b row 3

CodePudding user response:

with open(FILE) as file:
    contents = [row for row in csv.DictReader(file, delimiter=';')]
data = {
    'a': [row['columns B'] for row in contents if row['columns A'] == 'a'],
    'b': [row['columns B'] for row in contents if row['columns A'] == 'b']}

data
# >> {'a': ['row1', 'row2', 'row3'], 'b': ['row 1', 'row 2', 'row 3']}

Tested with Python3, but should work with Python2 as well. If not, please let me know.

  • Related