读取文件并将其转换为字典

时间:2021-02-26 19:16:34

标签: python

我有这个文本文件:

这是name_of_liquid(string)=amount(int)

liquid1=200

liquid2=20

liquid_X_= empty

liquid_3= 3000

现在,名称并不重要,但数量重要。它必须是一个整数。 如果它是 int 之外的任何其他类型,程序将引发异常

这是我的代码/伪代码:

#opening the file
d={}

try:
  dic = {}
  with open('accounts.txt') as f:
     for line in f:
        (key , val) = line.split()
        d[key] = int(val)
#except ValueError:
#    print('The value for', key,'is', value,' which is not a number!')

注释了 except 块,因为这是我的伪代码以及我如何计划处理 错误,但是当我在不使用异常处理的情况下运行此代码时,我收到“没有足够的值来解包”的错误 有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

试试这个

f = open("acounts.txt", "r")
dict = {}

try:
    for line in f:
        line = line.split("=")
        dict[line[0]] = int(line[1])
except:
print("Invalid value for key.")

答案 1 :(得分:1)

您应该使用 = 作为分隔符分割行并去除列表以去除多余的空格。

我个人认为在向字典中添加元素时应该使用 try catch 块。

以下代码应该可以解决您的问题。

d = {}
with open('accounts.txt', 'r') as f:
    for line in f:
        (key , val) = map(str.strip,line.split("="))
        try:
            d[key] = int(val)
        except ValueError:
            print('The value for', key,'is', val,' which is not a number!')