Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python上创建从字符串返回dict()的函数?_Python_Function_Dictionary - Fatal编程技术网

如何在Python上创建从字符串返回dict()的函数?

如何在Python上创建从字符串返回dict()的函数?,python,function,dictionary,Python,Function,Dictionary,我想创建一个函数,从txt文件中接收包含数据的字符串(str),并返回dict,如下所示: values = {'first' : 43, 'second': 42, ....} 但是我的密码打印出来了 {'first': '43'} {'second': '42'} {.....} 我用了Print() 我做到了,但这不是我想要的 有人能帮我吗 谢谢您的代码的问题是,您在每次迭代中都会创建一个新词典,覆盖上一个词典。 代码应如下所示: openfile = open('file.txt',

我想创建一个函数,从txt文件中接收包含数据的字符串(str),并返回dict,如下所示:

values = {'first' : 43, 'second': 42, ....}
但是我的密码打印出来了

{'first': '43'}
{'second': '42'}
{.....}
我用了Print()

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

有人能帮我吗


谢谢

您的代码的问题是,您在每次迭代中都会创建一个新词典,覆盖上一个词典。 代码应如下所示:

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

我希望这能回答你的问题

打印(值)
我做了。但是我想读取这个文件,这个函数返回一个命令,你应该发布一个数据文件的样本(前几行)好的,我编辑了ask。
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