python建立字典的程序_在python中动态创建字典

我想根据字符串动态构建字典.

我有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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值