0

I need to create a dictionary from a text file that contains comma-separated values.
So far I wrote this much.

import csv
pick = open('a.txt','r')
read = csv.reader(pick)
reviews = {}

The sample data in the text file looks like this

Peter,Gravity,4.5,For a Few Dollars More,1.0,Prometheus,4.0
Jack Holmes,Lawrence of Arabia,3.0,Gravity,3.5,The Godfather,1.5,Prometheus,5.0,The Guns of Navarone,3.0

And I want to create a dictionary that should look like this

{'Peter': {'Gravity': 4.5,
          'For a Few Dollars More': 1.0,
          'Prometheus': 4.0},

'Jack Holmes': {'Lawrence of Arabia': 3.0,
                'Gravity': 3.5,
                'The Godfather': 1.5,
                'Prometheus': 5.0,
                'The Guns of Navarone': 3.0,}
}

I looked on these pages: this this this this but didn't help to answer my question.
Could you give me some hints or ideas on how to accomplish this?

007mrviper
  • 459
  • 4
  • 20

2 Answers2

2

This solution uses zip to pair the keys and values for the interior dictionaries.

d = {}

with open('a.txt') as f:
    for line in csv.reader(f):
        it = iter(line)
        key = next(it)
        d[key] = dict(zip(it, it))

If you need float values, you can do something like

d[key] = dict((a, float(b)) for a, b in zip(it, it))
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

Here is a not so great but simple solution:

import csv

mydict = {}
with open('file.csv', mode='r') as infile:
    reader = csv.reader(infile)
    mylist = list(reader)
    for i in range(len(mylist)):
        z = iter(mylist[i][1:])
        mydict[mylist[i][0]] = dict(zip(z, z))

print(mydict)
Tshiteej
  • 121
  • 6