Reputation: 149
Everybody, hello,
I have a task to transfer list like random_list=['2018-01-01', 'google', 'cpc', 100]
(which could be expanded manually) into dictionary like {'2018-01-01': {'google': {'cpc': 100}}}
, which is also could be expanded more, if the list is expanded.
For example, if I would add any string or int in list - it should be included in dictionary and be like {'2018-01-01': {'google': {'cpc': {100: 'example'}}}}
, or {'2018-01-01': {'google': {'cpc': {'example': 100}}}}
.
I've travelled a lot on this stack overflow website, and there are questions like that, but nothing compared to "included dictionary". I'm a new user here, and maybe in future my skills of searching here will be upgraded, but I can't find anything similar. I can transform it into a simple dictionaries, but nothing compared to that.
Upvotes: 1
Views: 38
Reputation: 24282
You could also build it using functools.reduce:
from functools import reduce
random_list=['2018-01-01', 'google', 'cpc', 100]
reduce(lambda v, k: {k:v}, reversed(random_list[:-1]), random_list[-1])
# {'2018-01-01': {'google': {'cpc': 100}}}
We start with the initial value random_list[-1]
(100), which will be passed as value when we start iterating backward on the rest of the list. On the first iteration, the dict {'cpc': 100}
gets built.
On each following iteration, the already built dict gets passed as value to build the next level of the dict.
Upvotes: 1
Reputation: 147206
This can be done by recursion, using the first entry in the list as a key to a value which is a nested dictionary created from the rest of the list:
def make_dict(l):
if len(l) < 2:
return None
elif len(l) == 2:
return { l[0] : l[1] }
else:
return { l[0] : make_dict(l[1:]) }
print(make_dict(['2018-01-01', 'google', 'cpc', 100]))
print(make_dict(['2018-01-01', 'google', 'cpc', 100, 'example']))
Output:
{'2018-01-01': {'google': {'cpc': 100}}}
{'2018-01-01': {'google': {'cpc': {100: 'example'}}}}
Upvotes: 3