user32147
user32147

Reputation: 1073

Python writing two dictionaries with different value types into a single csv file using writerow

I have two dictionaries similar to samples below:

# First dictionary
dict_names = {}
dict_names[1] = 'Jane'
dict_names[2] = 'Alex'
dict_names[3] = 'Max'

# Second dictionary
dict_numList = {}
dict_numList[1] = [i for i in range(50)]
dict_numList[2] = [2*i for i in range(50)]
dict_numList[3] = [i*i for i in range(50)]

I would like to write to csv file where each row includes common key (in its first column, when opened using excel), string value from the first dictionary (in its second column), each element of the list value from the second dictionary (in its third column all the way to 52nd column).

I have attempted the code below, but it will write the entire number list into third column.

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter = ',')
    for key, val in dict_names.iteritems():
        csvwriter.writerow([key, val, [dict_numList[key][i] for i in range(0,50)]])

Any help would be greatly appreciated! Thanks

SOLUTION: given the answers, I have used the code below

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter = ',')
    for key, val in dict_names.iteritems():
        csvwriter.writerow([key, val] + dict_numList[key])

Upvotes: 1

Views: 98

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96236

If your comprehension is redundant, but keeping it for now, the following approach will suffice:

for key, val in dict_names.iteritems():
    row = [key, val]
    row.extend(dict_numList[key][i] for i in range(0,50))
    csvwriter.writerow(row)

Really, I believe you simply need:

for key, val in dict_names.iteritems():
    row = [key, val]
    row.extend(dict_numList[key])
    csvwriter.writerow(row)

Upvotes: 2

iUknwn
iUknwn

Reputation: 359

I think the problem is you're including a list in a list:

[key, val, [array of things]]

Instead of:

[key, val, thing 1, thing 2...]

You can simply append the two lists together with the + operator:

csvwriter.writerow([key, val] + [dict_numList[key][i] for i in range(0,50)])

Upvotes: 1

Related Questions