如何将严格排序的字符串列表转换成dict? [英] How to convert a strictly sorted list of strings into dict?

查看:109
本文介绍了如何将严格排序的字符串列表转换成dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个严格排序的字符串列表:

I have a strictly sorted list of strings:

['a',
 'b',
 'b/c',
 'b/d',
 'e',
 'f',
 'f/g',
 'f/h',
 'f/h/i',
 'f/h/i/j']

此列表与树表示类似。所以,我需要把它转换成dict:

This list is similar to tree representation. So, I need to convert it to dict:

{'a': {},
 'b': {'c': {},
       'd': {}},
 'e': {},
 'f': {'g': {},
       'h': {'i': {'j': {}}}}}

正如你所看到的,这个dict中的密钥是父母,价值观是孩子。

As you can see, keys in this dict are parents and values are children.

UPD:我同意空的dict

推荐答案

如果您不坚持作为叶值,您可以使用紧凑代码

If you don't insist on None as the leaf value, you can use the compact code

my_dict = lambda: defaultdict(my_dict)
d = my_dict()
for x in my_list:
    reduce(defaultdict.__getitem__, x.split("/"), d)

诚然,这并不是明确的代码,但它很简洁:)

Admittedly, it isn't that obvious what this code does, but it's succinct :)

这篇关于如何将严格排序的字符串列表转换成dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆