python - split a list with title value: pythonic way -


i have text, this:

[1] aaa bbb [2] ccc ddd 

what want:

{ 'title1': [ 'aaa', 'bbb' ],   'title2': [ 'ccc', 'ddd' ] } 

i can split text \n , use for , if statements this, no 'pythonic', elegance way this? kind of key ([1], [2]) limited.

edit: attempt here, , hard-coded:

item = string.split('\n') result = {}  in item:     # title item     if i[0] == '[':         name = re.sub(r'(\[|\])', '', item[i])         continue     # ...and put result dict     if name == '1':         if not 'breakfast' in result:             result['breakfast'] = []         result['breakfast'].push(value)     if name == '2':         if not 'lunch' in result:             result['lunch'] = []         result['lunch'].push(value)     if name == '3':         if not 'dinner' in result:             result['dinner'] = []         result['dinner'].push(value) 

from collections import defaultdict result = defaultdict(list) current_key = "error - missing title" open('youfile.txt', 'r') f:     line in f:         item = line.strip()         if item.strip('[]') != item:             current_key = item.strip('[]')         else:             result[current_key].append(item) 

if don't want use defaultdict can result = {} , change result[current_key].append(item) result.setdefault(current_key, []).append(item).


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -