I am new to python and trying to convert my input list which is ["a", "b", "c"]
into nested dictionaries like {"a":{"b":{"c":{}}}}
Asked
Active
Viewed 49 times
-6

Malik Faiq
- 433
- 6
- 18

M Usman Wahab
- 53
- 1
- 10
-
2Yes, with recursion for instance. – RemcoGerlich Sep 23 '19 at 13:00
-
2welcome to stackoverflow! please take the [tour](http://stackoverflow.com/tour), read up on [how to ask a question](https://stackoverflow.com/help/asking) and provide the [shortest program necessary to reproduce the problem](https://stackoverflow.com/help/minimal-reproducible-example). – hiro protagonist Sep 23 '19 at 13:00
-
1yes it's possible – DeepSpace Sep 23 '19 at 13:01
-
1Yes, this can be done. With `functools.reduce` it can even be done in one line. – Heike Sep 23 '19 at 13:13
-
@Heike please give me one line solution. – M Usman Wahab Sep 24 '19 at 05:46
-
One-liner, if you don't count that you need to `from functools import reduce`: `reduce(lambda y,x : {x: y}, reversed(my_list), {})` – Artog Sep 24 '19 at 05:58
1 Answers
0
You should probably not use this in production, but it was fun...
def make_dict_from_list(li):
temp = output = {}
for i, e in enumerate(li, 1):
if i != len(li):
temp[e] = {}
temp = temp[e]
else:
temp[e] = []
return output
print(make_dict_from_list(['a']))
print(make_dict_from_list(['a', 'b', 'c']))
Outputs
{'a': []}
{'a': {'b': {'c': []}}}

DeepSpace
- 78,697
- 11
- 109
- 154
-
-
@MUsmanWahab Because it's not very clear what it's doing and it's abusing some scoping "features" of Python. You should take a go at coming up with a recursive solution – DeepSpace Sep 23 '19 at 13:12