请帮我解决以下问题:我有逗号分隔的字符串和与这些字符串相关的值。昏迷的数量是不可预测的,并且可以被限制为6.我必须将其转换为python字典。例如:
aa.bb.cc 6 => mydict['aa']['bb']['cc']=6
aa.bb.dd.ee 8 = mydict['aa']['bb']['dd']['ee']=8
我的python版本是2.7.9
答案 0 :(得分:1)
一种方法是使用defaultdict
from collections import defaultdict as defd
dic = defd(dict)
def create_dict(astr):
keys, val = astr.split(' ')
keys = keys.split('.')
val = int(val)
prevdic = dic
for 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
答案 1 :(得分:0)
我假设你想要一本带有多个键的字典(你说" 一个字典"):
import re
s1 = 'a.bb.dd.ee 8'
s2 = 'aa.bb.cc 6'
def create_d(s):
fields = re.split(r'[. ]', s)
v = int(fields.pop())
d = { field:v for field in fields }
return d
mydict = create_d(s1)
print mydict
mydict.update(create_d(s2))
print mydict
给出:
{'a': 8, 'ee': 8, 'dd': 8, 'bb': 8}
{'a': 8, 'aa': 6, 'bb': 6, 'ee': 8, 'dd': 8, 'cc': 6}
答案 2 :(得分:-1)
您可以尝试使用简单的代码
str1 = 'aa.bb.cc 6'
str2 = 'aa.bb.cc.dd 8'
dictstr = {}
strdelim = str1.split(' ')
dictstr[tuple(strdelim[0].split('.'))] = strdelim[1]
strdelim = str2.split(' ')
dictstr[tuple(strdelim[0].split('.'))] = strdelim[1]
print dictstr
结果
{('aa', 'bb', 'cc'): '6', ('aa', 'bb', 'cc', 'dd'): '8'}