简体   繁体   English

将txt文件转换为python中的字典

[英]Convert txt file to a dictionary in python

I was trying to read a txt file and convert it to a dictionary in python, the txt file has list of countries with their per capita income eg "Quatar $129,700 Monaco $78,700,,,," when I tried to solve the problem the out put I am getting is " 'Quatar $129': 700 " I could not figure out why? 我尝试读取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)```

In your case: 在您的情况下:

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)

Generally, I would recommend to use the DictReader class in the built-in 'csv' module 通常,我建议在内置的“ csv”模块中使用DictReader

dictionary = {}

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

if you are looking to have the values as decimals you can strip off the "$" and cast it into an decimal by doing something like this 如果您希望将值设置为小数,则可以执行以下操作将“ $”剥离并转换为小数

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM