2

I have a csv file called "archive". It is opened as a reader. I wish to create a dictionary whose values (k,v) are made from {row[0]+row[2]:row[7]} for each row in the csv file. There must be a simple straight forward way to turn this csv into a dictionary where k = row[0]+row[2] and v = row[7].

# open archive reader
farchive = open ("wv5archive.csv","rb")
archive = csv.reader(farchive, delimiter=',')

for rows in archive: 
    arch_dict = {rows[0]+rows[2]:rows[7]} 

print arch_dict 

1 Answer 1

1

The easiest way to do this is to use a dictionary comprehension:

arch_dict = {row[0]+row[2]: row[7] for row in archive}

If you're on an older version of Python:

arch_dict = {}
for row in archive: 
    arch_dict[row[0]+row[2]] = rows[7]
2
  • You could write the comprehension pre 2.7 as dict( ((row[0],row[2]), row[7]) for row in archive) - more elegant than your second option (or row[0]+row[2] - whatever) Aug 6, 2012 at 16:09
  • "eye of the beholder" I guess. Your answer (to me) just seems to imply that you have to create an empty dict, and iterate to assign key/vals if not using 2.7+ - and we agree that's not the case... Anyway, +1 from me. Aug 6, 2012 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.