What is the best approach to get first row as key (dictionary) and rest of the row (values) in list python?

余生颓废 提交于 2021-02-10 14:43:43

问题


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 key in dictionary and test of the row as values?

Expected output:

{"Australia": ["test1","test2","address1"], "Hongkong": ["test2","test3","address2"]}

回答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']}



回答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)



回答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']}



回答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


来源:https://stackoverflow.com/questions/56132656/what-is-the-best-approach-to-get-first-row-as-key-dictionary-and-rest-of-the-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!