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.
For a
txt
file like soYou can just do
You can get rid of the
----...
line by just checking ifline.startswith('-----')
.EDIT - If you are sure that the first two lines contain the same stuff, then you can just do
This adds the first line to the
testDict
in the code and skips the first two lines and then continues on as normal.Your file should look like this:
Than you just need to add a bit of code:
You can read a file into a list of lines like this:
You can split a single line by spaces using:
Here's a principial example how to store a list into a dictionary:
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:
Here's my stab at it, tested on Python 2.x/3.x:
You should store the values as a list or a tuple. Something like this: