我有一个这种格式的文本文件:
key:object,
key2:object2,
key3:object3
如何将此转换为Python中的字典以用于以下过程?
s
=字典中的任何键s
=链接到上述密钥的对象。我尝试使用以下代码将它们用逗号分隔,但输出不正确。它将文本文件中的键和对象组合成一个单一的键和单个对象,有效地复制它:
代码:
file = open("foo.txt","r")
dict = {}
for line in file:
x = line.split(",")
a = x[0]
b = x[0]
dict[a] = b
输出错误:
key:object, key:object
key2:object2, key2:object2
key3:object3, key3:object3
谢谢
答案 0 :(得分:0)
m={}
for line in file:
x = line.replace(",","") # remove comma if present
y=x.split(':') #split key and value
m[y[0]] = y[1]
答案 1 :(得分:0)
# -*- coding:utf-8 -*-
key_dict={"key":'',"key5":'',"key10":''}
File=open('/home/wangxinshuo/KeyAndObject','r')
List=File.readlines()
File.close()
key=[]
for i in range(0,len(List)):
for j in range(0,len(List[i])):
if(List[i][j]==':'):
if(List[i][0:j] in key_dict):
for final_num,final_result in enumerate(List[i][j:].split(',')):
if(final_result!='\n'):
key_dict["%s"%List[i][0:j]]=final_result
print(key_dict)
我在“/ home / wangxinshuo / KeyAndObject”中使用你的文件
答案 2 :(得分:0)
您可以将文件内容转换为字典,其中包含类似下面的oneliner:
result = {k:v for k,v in [line.strip().replace(",","").split(":") for line in f if line.strip()]}
如果您希望字典值为stripped,只需添加v.strip()