Recursively build dictionaries from string characters

Viewed 120

I am working on a compression algorithm for a specific data structure and part of it requires changing a string into a dictionary as follows:

    "abc" => {'a':{'b':{'c':{}}}

Which is a group of nested dictionaries based on the letters of the word.

How can I do this in a recursive manner in python?

3 Answers

You can use recursion with list slicing:

def to_dict(d):
  return {} if not d else {d[0]:to_dict(d[1:])}

print(to_dict('abc'))

Output:

{'a': {'b': {'c': {}}}}

This is one way:

s = 'abc'
d = {}
current = d
for c in s:
    current = current.setdefault(c, {})
print(d)
# {'a': {'b': {'c': {}}}}

Here's a solution using reduce:

from functools import reduce

seq = 'abc'
result = reduce(lambda value, key: { key : value }, reversed(seq), {})

print(result)

Output

{'a': {'b': {'c': {}}}}
Related