0

I'm trying to get the output {'apple': '8.5', 'orange': '9.5'} But all I'm getting is {'apple': '8,5} {'orange' '9.5'} Any help would be really appreciated

example.txt:

name, price

apple 8.5

orange 9.5

name = "example.txt"
file = open(name, 'r')
next(file)                 
for line in file:  
    dict= {}    
    stripped_line = line.strip()
    data = stripped_line.split(" ")                  
    name = data[0]                
    price = data[1]                        
    dict[name] = price 
    print(prices)        
                          
fhand.close()            
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Faith
  • 1
  • 4

3 Answers3

3

change your code like below :

name = "example.txt"
file = open(name, 'r')
next(file)
mydict = {}
for line in file:
    stripped_line = line.strip()
    data = stripped_line.split(" ")
    name = data[0]
    price = data[1]
    mydict[name] = price
file.close()

print(mydict)

you'll have

{'apple': '8.5', 'orange': '9.5'}
Hadi Rahjoo
  • 175
  • 7
3

First, you should initiate the dict outside the for loop, because now it resets in each iteration. Second, I suggest you rename your dict variable, because dict is a keyword in python.

Ahmad
  • 349
  • 1
  • 9
0

Issue

As others have pointed out, you need to shift the dict variable outside the for loop. With your current implementation, each iteration will create a new dictionary which explains your result.

Adjusted code


file_name = 'example.txt'
result = None

# Using a context manager to read the file.
with open(file_name, 'r') as file:
    
    # Use list comprehension to trim and split each line.
    split_lines = [line.trim().split(' ') for line in file.readlines()]
    
    # Use dictionary comprehension to transform the split lines into dictionary.
    result = {data[0]: data[1] for line in split_lines}

print(result)

Resources

Raymond C.
  • 572
  • 4
  • 24