簡體   English   中英

將文本文件轉換成字典-Python

[英]convert text file into dictionary -Python

我得到了一個.txt文件,看起來像這樣。

2:雨3:奇5:是6:開始

我需要將其轉換為字典。

到目前為止,這是我所做的。

 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

但是,當我去打印字典時,它與{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