简体   繁体   中英

Read data from txt file in dictionary format

how do I convert a data read from a txt file in dictionary format.

Lines from txt file:

A1, 5, Apples
B1, 3, Oranges

Desired output:

{'A1':[5.0,'Apples'], 'B1':[3.0,'Oranges']}

only managed to code these:

fr = open('products.txt','r')
for line in fr.readlines():
    code, name, price = line.split(',')
    print(line)
    
    fr.close()

You can use comprehension:

result = {line.strip().split(',')[0]: [line.strip().split(',')[1], line.strip().split(',')[2]] for line in open('products.txt','r')}

Or without comprehension:

result = {}

with open('products.txt','r') as fr:
    for line in fr:
        parts = line.strip().split(',')
        result[parts[0]] = [parts[1], parts[2]]
print(result)
my_dict = {}
fr = open('products.txt','r')
    for line in fr.readlines():
        code, name, price = line.split(',')
        my_dict[code] = [name,price]
        print(line)
    
    fr.close()

You can create an empty dictionary and update the dictionary for each lines, also strip off the value for price to get rid of residue space after splitting on comma:

data = {}

fr = open('products.txt','r')
for line in fr.readlines():
    code, price, name = line.split(',')   # price is the middle item, name is last
    print(line)
    data.update({code:[float(price.strip()), name.strip()]})
    
fr.close()   #Keep this outside the loop

OUTPUT :

{'A1': [5.0, 'Apples'], 'B1': [3.0, 'Oranges']}

You're close, but you've got a few errors and a few missing things...

out_d = {}  # init an empty dict
fr = open('products.txt','r')
for line in fr.readlines():
    code, price, name = line.split(', ') # not code, name, price
    print(line)
    out_d[code] = [float(price), name]  # adds a new dict entry
fr.close()  # gets dedented
print(out_d)

A few things...
(1) according to your input file, you want to split on ', ' , not just ','
(2) it looks like the order of your input file is code/price/name not code/name/price
(3) you need to cast the price from string to float
(4) your fr.close() is indented too far. It needs to be dedented.

Also, it's fine to do an open() and close() when you're first starting out. But there is a better way to go, called a context manager, which will automatically do the close() for you. Basically, it would look like this:

out_d = {}  # init an empty dict
with open('products.txt','r') as fr:  # this creates a context
    for line in fr.readlines():
        code, price, name = line.split(', ') # not code, name, price
        print(line)
        out_d[code] = [float(price), name]
# fr.close() -- this line now goes away
print(out_d)

Above, the fr.close() line goes away, because the with open calls close when the with block finishes.

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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