I have a set of URLs like this:
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
And I need to create a tree-like dictionary that looks like this:
{
'example.com':
{
'one':
{
'two':
{
'three':
{
'four': None,
'five':
{
'six': None
}
},
'five': None
}
}
}
}
The URLs can have any number of levels, so the depth of the dictionary is not known beforehand.
How can I traverse over this dictionary to add the keys?
My current pseudo-code is:
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
Or is there a better way to do this? I have been trying for the past two days and could not get it done.
I've already searched through similar questions such as this one but they don't answer my question.