【问题标题】:How to create Function on Python to return a dict() from a string?如何在 Python 上创建函数以从字符串返回 dict()?
【发布时间】:2018-04-25 15:16:56
【问题描述】:

我想创建一个函数,它从 txt 文件中接收包含数据的字符串 (str) 并返回这样的字典:

values = {'first' : 43, 'second': 42, ....}

但是我的代码打印出来了

{'first': '43'}
{'second': '42'}
{.....}

我使用了 Print() ..

openfile = open('file.txt', 'r')
for lines in openfile :
dataf = lines.split('-')
dictionary = {}
dictionary[dataf[0] = dataf[1]
print(dictionary)

我做到了,但这不是我想要的。

有人可以帮我解决这个问题吗?

谢谢

【问题讨论】:

  • print(values)
  • 我做到了。但我想读取文件,这个函数返回字典
  • 您应该发布数据文件的样本(前几行)
  • 好的,我编辑了问题。

标签: python function dictionary


【解决方案1】:

您的代码的问题是您在每次迭代中创建一个新字典来覆盖前一个字典。 代码应该如下:

openfile = open('file.txt', 'r')
dictionary = {}                      #dictionary is created here
for lines in openfile :
  dataf = lines.split('-')
  dictionary[dataf[0]] = dataf[1]    #inserting into same dict
print(dictionary)                    #print the dict after inserting everything

我希望这能回答你的问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 2014-12-07
    • 2019-10-14
    • 2022-10-14
    • 2021-07-02
    • 1970-01-01
    • 2015-02-24
    • 2010-12-23
    相关资源
    最近更新 更多