0

I'm trying here to import CSV file which has data in just row 2 and I want to save it in a dictionary-based in it title mentioned in row 1.

My csv looks like this,

R1C1: 
name,task1,task2,task3

Row2Column1:
dave,allocation,field,supervision

and, if I have more tasks in Row2Column1, it should name task4 for the fourth task if I give. (eg):

R1C1: 
name,task1,task2,task3

Row2Colum1:
dave,allocation,field,supervision,manage

(manage task should be automatically named to task4)

import csv
path = "C:\\tasks.csv"
file = open(path, newline='')
reader = csv.reader(file)
header = next(reader)
data = []
for row in reader:

    name = row[0]
    tasks = row[1]
    data.append([name, tasks])

print(data)

Actual result:

[['dave', 'allocation']]

Expected:

{name: 'dave', task1: 'allocation', task2: 'field', task3: 'supervision', task4: 'manage'}}
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
ilexcel
  • 895
  • 8
  • 12
  • @PaulRooney, still not getting what is expected after using csv.DictReader – ilexcel Aug 02 '19 at 01:36
  • Your line `data = []` creates a list, why would you expect a dictionary? How do you expect your code to come up with `task` for tasks beyond the 3rd? Also, the expected dictionary you provided is not a valid Python `dict`, did you mean `{'name': 'dave', etc.}`? – Grismar Aug 02 '19 at 01:36
  • @Grismar exactly... how to modify for that in my existing code? – ilexcel Aug 02 '19 at 01:37
  • Can you clarify what the input looks like? What is `R1C1` and `Row2Colum1` etc. ? – Paul Rooney Aug 02 '19 at 01:39
  • Try using `csv.DictReader` - or just Google `read csv into dict python` and find many examples of people doing this. – Grismar Aug 02 '19 at 01:39
  • @Grismar, I tried and couldn't find a right answer there, that s why am here – ilexcel Aug 02 '19 at 01:41
  • @ilexcel its still muddying the waters wrt to what the input looks like. Its much clearer to show the input data than it is to try to explain it. Can you provide actual example input that can be loaded by the script? I'm guessing it might look like [this](https://pastebin.com/C2GujC8n) but I'm not sure. – Paul Rooney Aug 02 '19 at 01:43
  • @PaulRooney exactly the input looks like that – ilexcel Aug 02 '19 at 02:34

1 Answers1

0

As @Grismar said, you are appending a list on data when you should be using a dict instead...

By default, csv reader reads a row as a list. So you have the following:

header = ['name', 'task1', 'task2', 'task3']
tasks = [ <values> ]

If you want to add a dictionary, you can combine these two lists into one, as answered here: How do I combine two lists into a dictionary in Python?

Your code should have something that looks like this:

from itertools import izip_longest

data = {} # initialize as dictionary

for index, task in enumerate(izip_longest(header,tasks)):
    key = task[0]
    val = task[1]

    if key is None:
      key = "task%d" % (index + 1) # if there are more tasks than headers

    data[key] = val 
suitsense
  • 38
  • 3