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


i'm trying figure out how open file , store it's contents dictionary using part no. key , other information value. want this:

{part no.: "description,price", 453: "sperving_bearing,9900", 1342: "panametric_fan,23400",9480: "converter_exchange,93859"} 

i able store text file list, i'm not sure how assign more 1 value key. i'm trying without importing modules. i've been using basic str methods, list methods , dict methods.

for txt file so

453     sperving_bearing    9900 1342    panametric_fan      23400 9480    converter_exchange  93859 

you can do

>>> newdict = {} >>> open('testfile.txt', 'r') f:         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 rid of ----... line checking if line.startswith('-----').

edit - if sure first 2 lines contain same stuff, can do

>>> testdict = {"part no.": "description,price"} >>> open('testfile.txt', 'r') f:         _ = next(f)         _ = next(f)         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 first line testdict in code , skips first 2 lines , continues on normal.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -