[英]How to set the first item in a list to a dictionary key, and the following items as the value for that key?
Here is what I'm trying:这是我正在尝试的:
def dict1(filename):
try:
file_handle=open(filename,"r")
except FileNotFoundError:
return None
newdict = {}
for line in file_handle:
list1 = line.split(",")
(k, v) = list1
newdict[k]] = v
return newdict
The text file has lines like such:文本文件有这样的行:
cow 1,dog 1
john 1,rob 1,ford 1
robert 1,kyle 1,jake 1
I'm trying to create a dictionary like so:我正在尝试创建一个像这样的字典:
{'cow 1': ['dog 1'],
'john 1': ['rob 1','ford 1'],
'robert 1': ['kyle 1, 'jake 1']}
The problem is in the (k,v), how can i set the k to the first item in the list, and the v to all items following it?问题出在 (k,v) 中,如何将 k 设置为列表中的第一项,并将 v 设置为后面的所有项?
Using the csv
module.使用
csv
模块。
Ex:前任:
import csv
result = {}
with open(filename) as infile:
reader = csv.reader(infile)
for row in reader: #Iterate each row
result[row[0]] = row[1:] #column 0 as key and others as value.
print(result)
Output:输出:
{'cow 1': ['dog 1'],
'john 1': ['rob 1', 'ford 1'],
'robert 1': ['kyle 1', 'jake 1']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.