[英]Convert txt file to a dictionary in python
我尝试读取txt文件并将其转换为python中的字典,该txt文件中包含人均收入国家/地区列表,例如“ quattar $ 129,700 Monaco $ 78,700 ,,,,”,当我尝试解决输出问题时我得到的是“'Quatar $ 129':700“我不知道为什么?
with open("dict.txt") as file:
for line in file:
(key, val) = line.split()
dictionary[int(key)] = val
print (dictionary)```
在您的情况下:
with open("dict.txt") as file:
for line in file.readlines(): # readlines should split by '/n' for you
(key, val) = line.split(' ') # change delimiter to space, not default "," delimited
dictionary[int(key)] = val
print (dictionary)
通常,我建议在内置的“ csv”模块中使用DictReader类
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.