Python Twitter -- let's say I have a list and I want to convert that list to a Python dict with subkeys.
For example a list: ["og","image","width",1200]
I want to create a dict like:
d['og']['image']['width'] = 1200
Is there a glamourous way to do this?
Conversation
Replying to
I was thinking of starting with something like:
d = defaultdict(lambda: defaultdict(dict))
but kind of stuck on the logic after this point...
1
This Tweet was deleted by the Tweet author. Learn more
Replying to
The other issue is that the list could be an arbritary length but the last element is always the value for all the nested keys. But that's a helpful start!
1
Show replies
Replying to
idk if i'd call it "glamorous" but:
def nest(lst):
head, *tail = lst
if not tail:
return head
return {head: nest(tail)}
insert defaultdict as desired
1
1
i don't know of a way to do it with dict comprehensions and the like
1
Replying to
Does being a one-liner make it glamorous?
makeDict = lambda x: x[0] if len(x) == 1 else { x[0]: makeDict(x[1:]) }
1
4
Show replies
Show more replies



