How to read and store values from a text file into a dictionary. [python]

74,382

Solution 1

For a txt file like so

453     Sperving_Bearing    9900
1342    Panametric_Fan      23400
9480    Converter_Exchange  93859

You can just do

>>> newDict = {}
>>> with open('testFile.txt', 'r') as f:
        for line in f:
            splitLine = line.split()
            newDict[int(splitLine[0])] = ",".join(splitLine[1:])


>>> newDict
{9480: 'Converter_Exchange,93859', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}

You can get rid of the ----... line by just checking if line.startswith('-----').

EDIT - If you are sure that the first two lines contain the same stuff, then you can just do

>>> testDict = {"Part no.": "Description,Price"}
>>> with open('testFile.txt', 'r') as f:
        _ = next(f)
        _ = next(f)
        for line in f:
            splitLine = line.split()
            testDict[int(splitLine[0])] = ",".join(splitLine[1:])       
>>> testDict
{9480: 'Converter_Exchange,93859', 'Part no.': 'Description,Price', 453: 'Sperving_Bearing,9900', 1342: 'Panametric_Fan,23400'}

This adds the first line to the testDict in the code and skips the first two lines and then continues on as normal.

Solution 2

You can read a file into a list of lines like this:

lines = thetextfile.readlines()

You can split a single line by spaces using:

items = somestring.split()

Here's a principial example how to store a list into a dictionary:

>>>mylist = [1, 2, 3]
>>>mydict = {}
>>>mydict['hello'] = mylist
>>>mydict['world'] = [4,5,6]
>>>print(mydict)

Containers like a tuple, list and dictionary can be nested into each other as their items.

To itereate a list you have to use a for statement like this:

for item in somelist:
    # do something with the item like printing it
    print item
Share:
74,382
Harry Harry
Author by

Harry Harry

Updated on July 24, 2020

Comments

  • Harry Harry
    Harry Harry over 3 years

    I'm trying to figure out how to open up a file and then store it's contents into a dictionary using the Part no. as the key and the other information as the value. So I want it to look something like this:

    {Part no.: "Description,Price", 453: "Sperving_Bearing,9900", 1342: "Panametric_Fan,23400",9480: "Converter_Exchange,93859"}
    

    I was able to store the text from the file into a list, but I'm not sure how to assign more than one value to a key. I'm trying to do this without importing any modules. I've been using the basic str methods, list methods and dict methods.