python - Splitting lines read from file into dictionary key-value pairs -


i have file in following format:

key1/value1 key2/value2 key3/value3 ... 

i want read dictionary. have written following code accomplishes this:

 open(filename, 'r') dir_file:     return {line.split('/')[0]: line.split('/')[1] line in dir_file.readlines()} 

however, seems me invoking split() method twice bad code, , there must simpler/better way split line key-value pair i'm missing here.

thank in advance!

use following:

>>> open('my_file.txt', 'r') f: ...     d = dict(line.strip().split('/') line in f) ... >>> >>> d {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'} 

strip() used remove \n @ end of each line.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -