user2558589
user2558589

Reputation: 53

How to convert multiple lists to dictionaries in python?

['*a*', '*b*', '*c*', '*d*', '*f*','*g*']
['11', '22', '33', '44', '', '55']
['66', '77', '88', '', '99', '10']
['23', '24', 'sac', 'cfg', 'dfg', '']

need to put in dictionary as:

{a : ('11','66','23'),b : ('22','77','24'),c : ('33','88','sac'),d :('44','','cfg')}

The rows are read from a CSV file:

import csv
csvFile = csv.reader(open("sach.csv", "rb"))
for row in csvFile:
    print row

code which is tried shown above, The output of row is shown above which has many lists. please help me to put it in dictionary format as shown above.

Upvotes: 1

Views: 96

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124788

Zip the rows:

with open("sach.csv", "rb") as csv_infile:
    reader = csv.reader(csv_infile)
    yourdict = {r[0].replace('*', ''): r[1:] for r in zip(*reader)}

The zip() function does the pairing for you, by passing in the reader object with the * argument Python will loop over the CSV rows and pass each row as a separate argument to zip().

Upvotes: 7

Related Questions