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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With