What Is The Best Approach To Get First Row As Key (dictionary) And Rest Of The Row (values) In List Python?
From the test.csv file, I have country,first_name,last_name,address Australia,test1,test2,address1 Hongkong,test2,test3,address2 How can I read the csv file and assign country as
Solution 1:
Use a dictionary comprehension
txt= '''country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2'''
{line.split(',')[0] : line.split(',')[1:] for line in txt.split('\n')[1:]}
# {'Australia': ['test1', 'test2', 'address1'], 'Hongkong': ['test2', 'test3', 'address2']}
Solution 2:
The following is a rather simple example of how you can do this. First opening a file and creating an empty dictionary. Next we can work with each line of your file independently using a for loop. Then, for each line you strip
any extra nonsense on the end (such as \n
) then split
your line up based on your delimiter (,
). Set the first element of this list to the key and the rest t the value of your dictionary.
a = open("textfile.txt")
mydict = {}
for i in a:
j = i.strip("\n").split(",")
mydict[j[0]] = j[1:]
print(mydict)
Solution 3:
You can use csv
module for creating your dictionary, open the file using csv.reader
, and build the dictionary as you iterate throw the rows.
import csv
dct = {}
#Open csv file
with open('test.csv') as fp:
#Open reader instance
reader = csv.reader(fp)
#Skip header
next(reader)
#Iterate through rows and update dictionaries as you go
for row in reader:
dct[row[0]] = row[1:]
print(dct)
So if the file looks like
country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2
The output will be
{'Australia': ['test1', 'test2', 'address1'],
'Hongkong': ['test2', 'test3', 'address2']}
Solution 4:
this is an option using the csv
module with a dict-comprehension:
from csv import reader
with open('test.csv') as file:
lines = reader(file)
next(lines) # skip the header
dct = {row[0]: row[1:] for row in lines}
# {'Australia': ['test1', 'test2', 'address1'],
# 'Hongkong': ['test2', 'test3', 'address2']}
assuming that test.csv
looks like
country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2
Post a Comment for "What Is The Best Approach To Get First Row As Key (dictionary) And Rest Of The Row (values) In List Python?"