简体   繁体   中英

Reading values from file and storing them in dictionary

I want to write a function read_file() to read the values in the file and store the data in the a dictionary. The dictionary will look something like this:

product = {'d01':['pencil', 5], 'd02':['highlighter', 7], 'd03':['sharpener', 10]....}

What the items in the file looks like:

input:

d={}
file=r"C:\Users\Public\Documents\Folder\products.dat"
with open(file,'r') as f:
    for items in f:
       print(items)

results:

d01,pencil,5
d02,highlighter,7
d03,sharpener, 10
d04,pen,3

Here are my codes:

def read_file():
 d={}
 file=r"C:\Users\Public\Documents\Folder\products.dat"
 with open(file,'r') as f:
    for items in f:
       stuff = items.split(",")
       quantity = int(stuff[2].rstrip())
       a = stuff[0]
       b = [stuff[1], quantity]
       d = {a:b}
       print(d)
read_file()

Currently results I got:

{'d01': ['pencil', 5]}
{'d02': ['highlighter', 7]}
{'d03': ['sharpener', 10]}
{'d04': ['pen', 3]}

How do I achieve the above results?

Don't create a new dictionary for each line, add an element to the same dictonary.

Change

d = {a:b}

to

d[a] = b

And put print(d) after the loop is done, not inside the loop.

To read and parse a csv file into a dictionary of lists, using the first item on each line as a key and the remaining items on each line as a value list:

import csv
def parse(csvfilename):
    dic = {}
    with open(csvfilename, "r") as csvfile
        csvreader = csv.reader(csvfile, skipinitialspace=True)
        for row in csvreader:
            table[row[0]] = row[1:]
    return dic

在此处输入图像描述

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