我想根据字符串动态构建字典.
我有5个字符串:
ABC
ABC BCD DEF
ABC BCD FGH
ABC BCD FGH IJK
ABC DEF GHI
我想将其创建为字典:
dict = {
"ABC" : {
"BCD": {"DEF": {}, "FGH":{IJK}},
"DEF": {"GHI"},
}
}
到目前为止,这是我尝试过的方法,但是如果出现密钥错误,我不确定如何创建新密钥.
# orgs = list of string from about
for org in orgs:
org_path_sp = org .strip().split()
org_cur = org_dict
for org_el in org_path_sp:
try:
org_cur = org_cur[org_el.strip()]
except KeyError:
pass
# create the new entry
解决方法:
您走在正确的轨道上.您应该做的是每次构造一个空字典,以防键丢失:
org_dict = {}
for org in orgs.split('\n'):
org_path_sp = org .strip().split()
org_cur = org_dict
for org_el in org_path_sp:
org_el = org_el.strip()
if org_el not in org_cur:
org_cur[org_el] = org_cur = {}
else:
org_cur = org_cur[org_el]
或者我们可以稍微更改您的代码:
org_dict = {}
for org in orgs.split('\n'):
org_path_sp = org .strip().split()
org_cur = org_dict
for org_el in org_path_sp:
org_el = org_el.strip()
try:
org_cur = org_cur[org_el]
except KeyError:
org_cur[org_el] = org_cur = {}
例如:
>>> orgs = '''ABC
... ABC BCD DEF
... ABC BCD FGH
... ABC BCD FGH IJK
... ABC DEF GHI'''
>>> org_dict = {}
>>>
>>> for org in orgs.split('\n'):
... org_path_sp = org .strip().split()
... org_cur = org_dict
... for org_el in org_path_sp:
... org_el = org_el.strip()
... if org_el not in org_cur:
... org_cur[org_el] = org_cur = {}
... else:
... org_cur = org_cur[org_el]
...
>>> org_dict
{'ABC': {'BCD': {'DEF': {}, 'FGH': {'IJK': {}}}, 'DEF': {'GHI': {}}}}
这里的内部元素不是集合,而是字典.在这里使用字典会更有意义,因为如果您以后要更新元素并添加额外的组织,那么我们可以轻松地在部分填充的字典上再次运行Thins程序.
请注意,字典是无意义的.因此,不能保证结果中键的顺序.如果需要,可以使用OrderedDict.例如:
from collections import OrderedDict
org_dict = OrderedDict()
for org in orgs.split('\n'):
org_path_sp = org .strip().split()
org_cur = org_dict
for org_el in org_path_sp:
org_el = org_el.strip()
if org_el not in org_cur:
org_cur[org_el] = org_cur = OrderedDict()
else:
org_cur = org_cur[org_el]
这将导致:
>>> pprint(org_dict)
OrderedDict([('ABC',
OrderedDict([('BCD',
OrderedDict([('DEF', OrderedDict()),
('FGH',
OrderedDict([('IJK',
OrderedDict())]))])),
('DEF', OrderedDict([('GHI', OrderedDict())]))]))])
我们可以将它们转换回字典,但是顺序将再次丢失.
标签:python,django
来源: https://codeday.me/bug/20191108/2010377.html