【问题标题】:Read from file and add to dictionary without lists从文件中读取并添加到没有列表的字典
【发布时间】:2020-08-27 16:10:55
【问题描述】:

Thie 是我的文本文件的一个示例:

A, 100 101 102
B, 103 104

我想从这个文件中读取并创建一个字典。

这是我的代码:

def readFromFile():
d = {} # empty dictionary
with open('file.txt') as fr: #read from text file
    for line in fr.readlines(): # reading text file by line
        k, v = line.split(',') # splitting the line on text file by ',' to define the key and values
        v = v.split() # splitting the values in each key into a list
        for n in range( len(v) ): 
            v[n] = int(v[n]) # convert student id in list from str to int
        d[k] = v # build dictionary with keys and its values
return d

这是我的输出的样子:

{'A': [100, 101, 102], 'B': [103, 104]}

我想使用这个函数用 int 209 更新 A 的值:

def writeToFile(d):
with open('file.txt', 'w') as fw:
    for k,v in d.items():
        print(f'{k}, {v}', file = fw)

我的文件会这样写:

A, [100, 101, 102, 209]

这会导致函数 readFromFile() 抛出错误,因为文本文件不再是相同的格式。

文本文件的期望输出是这样的:

A, 100 101 102 209

【问题讨论】:

  • 我认为 dict 不可能。
  • 你不能。这是无效的语法,它只是其他地方 XY 问题的症状
  • 你专注于错误的事情。电流输出没有问题。你用它做什么很可能是你的问题
  • 也许你可以这样做{'A': '100, 101, 102', 'B':' 103, 104'},但不能这样做{'A': 100, 101, 102, 'B': 103, 104}
  • 谢谢。我真正的问题是当我更新字典时尝试在原始文件上写。例如,我用 int 209 更新 A 的值。我希望能够在文本文件上写为 A, 100 101 102 209。此时,它将始终写为:A, [100, 101, 102, 209]

标签: python dictionary split file-handling strip


【解决方案1】:

问题是您没有以预期的格式写入文件。您需要编写与您阅读的格式相同的格式。

def write_to_file(filename, d):
    with open(filename, 'w') as fw:
        for k,v in d.items():
            line_data = ' '.join(map(str, v))
            print('{}, {}'.format(k, line_data), file = fw)

您的 readFromFile 函数不会验证格式。所以它当然会抛出错误——只要捕获任何错误并将其报告为错误的文件内容。

要扩展 line_data,您希望将一个列表组合成一个字符串,用空格分隔,因此您将使用空格作为分隔符,并在调用 https://docs.python.org/3/library/stdtypes.html#str.join 时将列表作为可迭代对象

当然,你不能使用 str.join 来连接整数。您需要将它们全部转换为 str,因此您将 map(str, v) 作为要加入的可迭代对象传递给它。内置函数 https://docs.python.org/3/library/functions.html#map 只是对每个项目应用一个函数(在本例中转换为 str)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2017-04-21
    • 2011-12-25
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多