简体   繁体   English

将文本文件转换成字典-Python

[英]convert text file into dictionary -Python

I am given a .txt file which looks like this.. 我得到了一个.txt文件,看起来像这样。

2:rain 3:odd 5:yes 6:go 2:雨3:奇5:是6:开始

I need to convert it into a dictionary. 我需要将其转换为字典。

This is what I have done so far. 到目前为止,这是我所做的。

 words_dict = {}
 file = open(filename, "r")
 for word in file:
      k, v = word.split(":")
      words_dict[k.strip()] = v.strip()                
 file.close()
 return words_dict

However, when i go and print the dictionary it does not match my expected output of {2: 'rain', 3: 'odd', 5: 'yes', 6: 'go'} 但是,当我去打印字典时,它与{2:'rain',3:'odd',5:'yes',6:'go'}的预期输出不匹配

l="2:rain 3:odd 5:yes 6:go".split()
{x.split(":")[0]:x.split(":")[1]  for x in l}
list_ = [x for x in open('text.txt').read().split()]

dict_ = {k: v for k, v in [x.split(':') for x in list_]}


# list_ = ['2:rain', '3:odd', '5:yes', '6:go']
# dict_ = {'2': 'rain', '3': 'odd', '5': 'yes', '6': 'go'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM