1

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 e.g "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?

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

print (dictionary)```
Mikias Hundie
  • 107
  • 1
  • 2
  • 11
  • In your posted example, you should split by either spaces or `$`... `line.split("$")`... What is happening is that it looks like your split is using commas. I can provide an example if you need past that – ViaTech Apr 02 '19 at 00:15
  • change `file` variable to something else besides overwriting a python built-in keyword, and use `dictionary[key] = val`, then your code appears to work as expected. Produces output: `{'Quatar': '$129,700', 'Monaco': '$78,700'}` See demo: https://repl.it/@downshift/DutifulBadAmpersand – chickity china chinese chicken Apr 02 '19 at 00:16
  • https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary – Sachit Nagpal Apr 02 '19 at 00:30

2 Answers2

3

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

skullgoblet1089
  • 554
  • 4
  • 12
1
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))
Chris Long
  • 46
  • 4