python - auction script (input from file to dictionary) -


so have file, example:

book peter 500 george peterson 300 notebook lizzie 900 jack 700 

the integers bids prizes. want read names , bids dictionary, got stuck here:

d = {} open('adat.txt') f:     d = dict(x.rstrip().split(none, 1) x in f) keys,values in d.items():     print(keys)     print(values) 

so, how read data in correctly?

you need skip on "invalid" lines book , notebook:

d = {} open('adat.txt') f:     line in f:         words = line.split()         try:             price = int(words[-1])             name = ' '.join(words[:-1])             d[name] = price         except (valueerror, indexerror):             # line doesn't end in price (int() raised valueerror)             # or empty (words[-1] raised indexerror)             pass  key, value in d.items():     print(key)     print(value) 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -