使用可变数量的键遍历字典

时间:2018-01-04 12:08:22

标签: python dictionary recursion graph traversal

我有一组这样的网址:

http://example.com/one/two/three/four/
http://example.com/one/two/three/five/
http://example.com/one/two/three/five/six
http://example.com/one/two/five

我需要创建一个类似于树的字典:

{
    'example.com': 
    {
        'one': 
        {
            'two':
            {
                'three':
                {
                    'four': None,
                    'five': 
                    {
                        'six': None
                    }
                },
                'five': None
            }
        }
    }
}

网址可以任意数量的级别,因此事先不知道字典的深度。

如何遍历此词典以添加密钥?

我当前的伪代码是:

list_of_links = [
    'http://example.com/one/two/three/four/',
    'http://example.com/one/two/three/five/',
    'http://example.com/one/two/three/five/six',
    'http://example.com/one/two/five',
]

dic = {'example.com':None}

for link in list_of_links: 
    url_path = urlparse.urlparse(link).path
    url_path_parts = url_path.split('/')

    curr_dic_path = 'example.com'
    for segment in url_path_parts:

        # How to do this?
        if segment in dic's current path:
            curr_dic_path = curr_dic_path + segment
        else
            add_segment_to_dic_current_path

或者有更好的方法吗?过去两天我一直在尝试,但无法完成。

我已经搜索了this one等类似问题,但他们没有回答我的问题。

0 个答案:

没有答案
相关问题