【问题标题】:How to add to a dictionary through a text file如何通过文本文件添加到字典
【发布时间】:2013-12-17 19:47:17
【问题描述】:

我想通过文本文件添加到字典中。基本上我的文本文件是这样的:

year3test 0
year4test 0
year5test 0
year6test 0

我想将这些添加到标题为 totals = {} 的空白字典中,其中 year3test,year4test 是键,0 是总数,因此我的字典如下所示:

totals = {
"year3test" : 0
"year4test" : 0
"year5test" : 0
"year6test" : 0
}

我应该怎么做?抱歉,我对python很陌生。

【问题讨论】:

  • 欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。您提供的详细信息越多,您可能收到的答案就越多。
  • python 文档是一个很好的起点...docs.python.org/2/tutorial/…

标签: python file text dictionary


【解决方案1】:
dict(line.split() for line in open('path/to/input'))

或者,更详细的方式:

with open('path/to/input') as infile:
    answer = {}
    for line in infile:
        k,v = line.split()
        answer[k] = v

【讨论】:

  • 在详细的方式上,当我使用它时,我收到一个错误消息“k, v = line.split TypeError: 'builtin_function_or_method' object is not iterable”
【解决方案2】:

评估?

#!/usr/bin/python

a = {'hello':1,'what':2,'which':3} #a is dict

with open ("file1.txt","w") as f:
    f.write ('%s' % a) # creating file.  you may type it to see how it made (text)

b = ''
with open ("file1.txt","r") as f:
    b = eval(f.read()) # reading dict file and converting it to dict.

print type(b) # b is dict.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多