python列表嵌套字典append,从Python中的多个嵌套字典/列表创建树

前言:为了帮助解释我为什么要这样做,我将解释最终目标。实际上,我有一个用非常特殊的语法定义的帐户列表。以下是一些示例:Assets:Bank:Car

Assets:Bank:House

Assets:Savings:Emergency

Assets:Savings:Goals:Roof

Assets:Reserved

如上所示,一个帐户可以有任意数量的父母和子女。最终目标是用Python将上述帐户解析为一个树结构,该结构将用于在Sublime文本编辑器中提供帐户自动完成(即,如果我键入Assets:,然后查询auto complete,我将看到一个列表,如下所示:Bank,Savings,Reserved)

结果:使用序言中的account list,Python中所需的结果如下所示:

^{pr2}$

半解:我可以使用递归将两个基本帐户相加。这适用于添加这两个:Assets:Bank:Car和Assets:Bank:House。然而,一旦它们开始不同,它就开始崩溃,递归变得混乱,所以我不确定这是否是最好的方法。在import re

def parse_account(account_str):

subs = account_str.split(":")

def separate(subs):

if len(subs) == 1:

return subs

elif len(subs):

return [{subs[0]: separate(subs[1:])}]

return separate(subs)

def merge_dicts(a, b):

# a will be a list with dictionaries and text values and then nested lists/dictionaries/text values

# b will always be a list with ONE dictionary or text value

key = b[0].keys()[0] # this is the dictionary key of the only dictionary in the b list

for item in a: # item is a dictionary or a text value

if isinstance(item, dict): # if item is a dictionary

if key in item:

# Is the value a list with a dict or a list with a text value

if isinstance(b[0][key][0], str):

# Extend the current list with the new value

item[key].extend(b[0][key])

else:

# Recurse to the next child

merge_dicts(item[key], b[0][key])

else:

return a

# Accounts have an "open [name]" syntax for defining them

text = "open Assets:Bank:Car\nopen Assets:Bank:House\nopen Assets:Savings:Emergency\nopen Assets:Savings:Goals:Roof\nopen Assets:Reserved"

EXP = re.compile("open (.*)")

accounts = EXP.findall(text) # This grabs all accounts

# Create a list of all the parsed accounts

dicts = []

for account in accounts:

dicts.append(parse_account(account))

# Attempt to merge two accounts together

final = merge_dicts(dicts[0], dicts[1])

print final

# In the future we would call: reduce(merge_dicts, dicts) to merge all accounts

我可能会以完全错误的方式去做这件事,我会对不同的意见感兴趣。否则,是否有人了解如何使用示例字符串中的其余帐户进行此操作?在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值