How to convert coma delimited string into python dictionary? -
please me following issue: have coma delimited strings , value related these strings. number of comas unpredictable , can limited 6. have convert python dictionary. example:
aa.bb.cc 6 => mydict['aa']['bb']['cc']=6 aa.bb.dd.ee 8 = mydict['aa']['bb']['dd']['ee']=8
my python version 2.7.9
one way use defaultdict
from collections import defaultdict defd dic = defd(dict) def create_dict(astr): keys, val = astr.split(' ') keys = keys.split('.') val = int(val) prevdic = dic j, k in enumerate(keys): if j == len(keys)-1: prevdic[k] = val elif k not in prevdic: prevdic[k] = defd(dict) prevdic = prevdic[k] create_dict('aa.bb.cc 6') create_dict('aa.bb.dd.ee 8') dic['aa']['bb']['cc'] ## returns 6 dic['aa']['bb']['dd']['ee'] ## returns 8
Comments
Post a Comment