Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在列表python中,获取第一行作为键(字典)和其余行(值)的最佳方法是什么?_Python 3.x - Fatal编程技术网

Python 3.x 在列表python中,获取第一行作为键(字典)和其余行(值)的最佳方法是什么?

Python 3.x 在列表python中,获取第一行作为键(字典)和其余行(值)的最佳方法是什么?,python-3.x,Python 3.x,从test.csv文件中,我有 country,first_name,last_name,address Australia,test1,test2,address1 Hongkong,test2,test3,address2 如何读取csv文件并在字典中将国家指定为键,将行的测试指定为值 预期产出: {"Australia": ["test1","test2","address1"], "Hongkong": ["test2","test3","address2"]} 使用字典理解 txt

从test.csv文件中,我有

country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2
如何读取csv文件并在字典中将国家指定为键,将行的测试指定为值

预期产出:

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

使用字典理解

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

这是一个使用具有dict理解的模块的选项:

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']}
假设
test.csv
看起来像

country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2
country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2

下面是一个非常简单的示例,说明了如何做到这一点。首先打开一个文件并创建一个空字典。接下来,我们可以使用for循环独立地处理文件的每一行。然后,对于每一行,您
在结尾处去除任何多余的废话(例如
\n
),然后
根据您的分隔符(
)分割您的行。将此列表的第一个元素设置为键,其余元素设置为字典的值

a = open("textfile.txt")
mydict = {}
for i in a: 
    j = i.strip("\n").split(",")
    mydict[j[0]] = j[1:]

print(mydict)

您可以使用
csv
模块创建字典,使用
csv.reader
打开文件,并在迭代抛出行时构建字典

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)
所以如果文件看起来像

country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2
country,first_name,last_name,address
Australia,test1,test2,address1
Hongkong,test2,test3,address2
输出将是

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