Python 3.x 将txt文件转换为python中的字典

Python 3.x 将txt文件转换为python中的字典,python-3.x,Python 3.x,我试图读取一个txt文件并将其转换为python词典,txt文件中列出了人均收入为129700美元的国家,摩纳哥78700美元,,,,,当我试图解决这个问题时,我得到的结果是“129美元”:700我不明白为什么 with open("dict.txt") as file: for line in file: (key, val) = line.split() dictionary[int(key)] = val print (dictionary)``` 就你而言: 使用op

我试图读取一个txt文件并将其转换为python词典,txt文件中列出了人均收入为129700美元的国家,摩纳哥78700美元,,,,,当我试图解决这个问题时,我得到的结果是“129美元”:700我不明白为什么

with open("dict.txt") as file:
for line in file:
    (key, val) = line.split()
    dictionary[int(key)] = val

print (dictionary)```
就你而言:

使用opendict.txt作为文件: 对于file.readlines中的行:readlines应按“/n”进行拆分 键,val=行。拆分“”将分隔符更改为空格,而不是默认分隔符 字典[intkey]=val 印刷词典 通常,我建议在您的案例中使用内置的“csv”模块中的类:

dictionary = {}

with open("dict.txt") as file:
for line in file:
    (key, val) = line.split()
    dictionary[key] = val
使用opendict.txt作为文件: 对于file.readlines中的行:readlines应按“/n”进行拆分 键,val=行。拆分“”将分隔符更改为空格,而不是默认分隔符 字典[intkey]=val 印刷词典 通常,我建议在内置的“csv”模块中使用该类

dictionary = {}

with open("dict.txt") as file:
for line in file:
    (key, val) = line.split()
    dictionary[key] = val
如果您希望将这些值设置为小数,您可以通过执行以下操作将$去掉并转换为小数

from decimal import Decimal
from re import sub

dictionary = {}

with open("dict.txt") as file:
for line in file:
    (key, val) = line.split()
    dictionary[key] = Decimal(sub(r'[^\d.]', '', val))
如果您希望将这些值设置为小数,您可以通过执行以下操作将$去掉并转换为小数

from decimal import Decimal
from re import sub

dictionary = {}

with open("dict.txt") as file:
for line in file:
    (key, val) = line.split()
    dictionary[key] = Decimal(sub(r'[^\d.]', '', val))

在您发布的示例中,您应该按空格或$。。。行。拆分$。。。发生的情况是,您的拆分似乎使用了逗号。我可以提供一个例子,如果除了覆盖python内置关键字之外,您还需要使用pass thatchange file变量,并使用dictionary[key]=val,那么您的代码似乎可以按预期工作。生成输出:{'Quatar':'$129700','Monaco':'$78700'}请参见演示:在您发布的示例中,您应该按空格或$分割。。。行。拆分$。。。发生的情况是,您的拆分似乎使用了逗号。我可以提供一个例子,如果除了覆盖python内置关键字之外,您还需要使用pass thatchange file变量,并使用dictionary[key]=val,那么您的代码似乎可以按预期工作。产生输出:{'Quatar':'129700美元','摩纳哥':'78700美元'}见演示: