Home > Software design >  Output should have produced 1 dictionary python
Output should have produced 1 dictionary python

Time:05-31

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()            

CodePudding user response:

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.

CodePudding user response:

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'}

CodePudding user response:

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

  • Related