Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read a csv into a dictionary in python?

I want to read from a csv file (psc.csv) which has two columns as below:

cellname,scrambling
UER1100A,128
UER1100B,129
UER1100C,130
UER1300A,1
UER1300B,2
UER1300C,3
UER1400H,128

and put the whole of this file into one dictionary so the dictionary will look like :

{'UER1100A': '128' , 'UER1100B': '129' , 'UER1100C': '130' ,  ...}

I tried to use csv module as below but it returns a mixed output and in separated dictionaries. What is the solution?
MyCode:

#!/usr/bin/python3
import csv
with open('psc.csv', newline='') as pscfile:
    reader = csv.DictReader(pscfile)
    for row in reader:
        print(row)
like image 825
John Smith Avatar asked Nov 22 '15 19:11

John Smith


1 Answers

Just add each row to a dictionary:

import csv

results = {}
with open('psc.csv', newline='') as pscfile:
    reader = csv.DictReader(pscfile)
    for row in reader:
        results[row['cellname']] = row['scrambling']

Rather than use a DictReader, I'd use a regular reader here and feed the result directly to a dict() call after skipping the first row:

import csv

with open('psc.csv',newline='') as pscfile:
    reader = csv.reader(pscfile)
    next(reader)
    results = dict(reader)  # pull in each row as a key-value pair
like image 174
Martijn Pieters Avatar answered Oct 25 '22 07:10

Martijn Pieters