0

I have a CSV file which I am opening through this code:

open(file,"r")

When I read the file I get the output:

['hello', 'hi', 'bye']
['jelly', 'belly', 'heli']
['red', 'black', 'blue']

I want the otput something like this:

{hello:['jelly','red'], hi:['belly','black'], 'bye':['heli','blue']}

but I have no idea how

user3029969
  • 127
  • 1
  • 2
  • 8

4 Answers4

2

You can use collections.defaultdict and csv.DictReader:

>>> import csv
>>> from collections import defaultdict
>>> with open('abc.csv') as f:
    reader = csv.DictReader(f)
    d = defaultdict(list)
    for row in reader:
        for k, v in row.items():
           d[k].append(v)
...            
>>> d
defaultdict(<type 'list'>,
{'hi': ['belly', 'black'],
 'bye': ['heli', 'blue'],
 'hello': ['jelly', 'red']})
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0
yourHash = {}

with open(yourFile, 'r') as inFile:
    for line in inFile:
        line = line.rstrip().split(',')
        yourHash[line[0]] = line[1:]

This assumes that each key is unique to one line. If not, this would have to be modified to:

yourHash = {}

with open(yourFile, 'r') as inFile:
    for line in inFile:
        line = line.rstrip().split(',')

        if line[0] in yourHash:
            yourHash[line[0]] += line[1:]
        else:
            yourHash[line[0]] = line[1:]

Of course, you can use csv, but I figured that someone would definitely post that, so I gave an alternative way to do it. Good luck!

Steve P.
  • 14,489
  • 8
  • 42
  • 72
0
csv = [
  ['hello', 'hi', 'bye'],
  ['jelly', 'belly', 'heli'],
  ['red', 'black', 'blue'],
]

csv = zip(*csv)

result = {}
for row in csv:
  result[row[0]] = row[1:]
Jorge Barata
  • 2,227
  • 1
  • 20
  • 26
0

You can use csv, read the first line to get the header, create the number of lists corresponding to the header and then create the dict:

import csv

with open(ur_csv) as fin:
    reader=csv.reader(fin, quotechar="'", skipinitialspace=True)
    header=[[head] for head in next(reader)]
    for row in reader:
        for i, e in enumerate(row):
            header[i].append(e)

data={l[0]:l[1:] for l in header}            
print(data)     
# {'hi': ['belly', 'black'], 'bye': ['heli', 'blue'], 'hello': ['jelly', 'red']}     

If you want something more terse, you can use Jon Clements excellent solution:

with open(ur_csv) as fin:
    csvin = csv.reader(fin, quotechar="'", skipinitialspace=True)
    header = next(csvin, [])
    data=dict(zip(header, zip(*csvin)))
    # {'bye': ('heli', 'blue'), 'hello': ('jelly', 'red'), 'hi': ('belly', 'black')}

But that will produce a dictionary of tuples if that matters...

And if you csv file is huge, you may want to rewrite this to generate a dictionary row by row (similar to DictReader):

import csv

def key_gen(fn):
    with open(fn) as fin:
        reader=csv.reader(fin, quotechar="'", skipinitialspace=True)
        header=next(reader, [])
        for row in reader:
            yield dict(zip(header, row))

for e in key_gen(ur_csv):
    print(e)
# {'hi': 'belly', 'bye': 'heli', 'hello': 'jelly'}
  {'hi': 'black', 'bye': 'blue', 'hello': 'red'}    etc...
Community
  • 1
  • 1
dawg
  • 98,345
  • 23
  • 131
  • 206