将文本文件转换成字典 [英] Convert a text file into a dictionary

查看:1144
本文介绍了将文本文件转换成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这种格式的文本文件:

I have a text file in this format:

key:object,
key2:object2,
key3:object3

如何通过以下步骤将其转换成Python字典?

How can I convert this into a dictionary in Python for the following process?

  1. 打开
  2. 检查字符串s =词典中的任何键
  3. 如果是,则字符串s =链接到上述键的对象.
  4. 否则,什么也没发生
  5. 文件关闭.
  1. Open it
  2. Check if string s = any key in the dictionary
  3. If it is, then string s = the object linked to the aforementioned key.
  4. If not, nothing happens
  5. File closes.

我尝试了以下代码以逗号分隔,但输出不正确.它使文本文件中的键和对象的组合成为单个键和单个对象,从而有效地复制了它:

I've tried the following code for dividing them with commas, but the output was incorrect. It made the combination of key and object in the text file into a single key and single object, effectively duplicating it:

代码:

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

谢谢

推荐答案

m={}                            
for line in file:
    x = line.replace(",","")     # remove comma if present
    y=x.split(':')               #split key and value
    m[y[0]] = y[1]

这篇关于将文本文件转换成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆