-2

If I had a text file with the following texts:

string, float

string 2, float 2

string 3, float 3

... and so on 

How would I turn this into a python dictionary?

Ultimately, I would like all of my strings to become the key and all of the floats to become the value.

I have tried turning this into a set, yet I was unable to get to where I wanted it to be.

I have also tried the following code, as I saw another post with a similar problem giving me this solution. Yet, I was unable to get it to print anything.

m={}   
for line in file:
    x = line.replace(",","")     # remove comma if present
    y=x.split(':')               #split key and value
    m[y[0]] = y[1]

                     

Thank you so much.

Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29

2 Answers2

0

If every line in the text file is formatted exactly as it is in the example, then this is what I would do:

m = {}
for line in file:
  comma = line.find(", ") # returns the index of where the comma is
  s = line[:comma] 
  f = line[comma+1:]

  m[s] = str.strip(f) # str.strip() removes the extra spaces 
tim
  • 52
  • 5
0

You need to research more. Don't be lazy.

m = {}

for line in file:
    (key, value) = line.split(',') # split into two parts
    m[key] = value.strip('\n')     # remove the line break and append to dictionary


# output
# {'string1': ' 10', 'string2': ' 11'}
Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29