[英]Converting a list to a dictionary troubles
I am reading lines from a file and appending each line to a list. 我正在从文件中读取行,并将每行追加到列表中。 This is fine, however I am having trouble going from ['A','B', 'C', 'D', ... 'last element'], ['A','B','C','D', ...'last element'], .... to {'A':['B','C','D', ... 'last element'], ....} I can separate the key I want in each line, but when I try to convert it to a dictionary it goes {'A':['last element'], ...}
很好,但是我在从['A','B','C','D',...'最后一个元素'],['A','B','C', 'D',...'last element'],....到{'A':['B','C','D',...'last element'],....}我可以在每一行中分隔想要的键,但是当我尝试将其转换为字典时,它会变成{'A':['last element'],...}
ct = 0
myKey = eachList[0]
for el in eachList:
subList = []
if ct != 0:
subList.append(eachList[ct])
myDict[myKey] = subList
ct+=1
I searched the forum, but the topics were either using ittertools/ izip or I just couldn't follow. 我在论坛上进行了搜索,但主题使用的是ittertools / izip,或者我只是听不懂。 Any help is appreciated!
任何帮助表示赞赏!
Here is a snippet of code, how you can simply read lines into a dictionary: 这是一段代码,您可以轻松地将行读入字典中:
final_dict = {}
with open('text.txt') as f:
for line in f.readlines():
raw = line.strip().split(',')
final_dict[raw[0]] = raw[1:]
Given the following input: 给出以下输入:
k1, v11, v12, v13
k2, v21, v22, v23
k3, v31, v32, v33
final_dict
will be: final_dict
将是:
{'k3': [' v31', ' v32', ' v33'], 'k2': [' v21', ' v22', ' v23'], 'k1': [' v11', ' v12', ' v13']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.