【问题标题】:convert text file into dictionary -Python将文本文件转换为字典-Python
【发布时间】:2023-03-15 14:28:02
【问题描述】:

我得到一个 .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'}

不匹配

【问题讨论】:

  • 你得到什么输出?
  • {'2': 'rain'} {'2': 'rain', '3': 'odd'} {'5': 'yes', '2': 'rain' , '3': 'odd'} {'5': 'yes', '2': 'rain', '3': 'odd', '6': 'go'} {'5': 'yes' , '2': '雨', '3': '奇数', '6': '去'} [] {'5': [], '2': [], '3': [], ' 6': []}

标签: python-3.x dictionary


【解决方案1】:
l="2:rain 3:odd 5:yes 6:go".split()
{x.split(":")[0]:x.split(":")[1]  for x in l}

【讨论】:

    【解决方案2】:
    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'}
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2023-03-20
      • 2020-09-24
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      相关资源
      最近更新 更多