Riptyde4
Riptyde4

Reputation: 5480

convert list of keys to nested dictionary

I'm trying to figure out how to create, for example, a dictionary that looks like this: d[keys[0]][keys[1]][keys[2]] from a list like this : keys = ["key1", "key2", "key3"] ...

I've tried the following:

  keys = ["key1", "key2", "key3"]
  d = {}
  d_ref= d
  for key_num, key in enumerate(keys):
    if key_num < len(keys)-1:
      d[key] = {}
      d_ref = d[key]
    else:
      d_ref[key] = []
  print(d)

but it results in this:

{'key1': {}, 'key2': {'key3': []}}

I'm aiming for this output:

{'key1' : { 'key2' : { "key3" : [] } } }

Update

Thanks to wim for the answer that led me to my desired result:

keys = ["key1", "key2", "key3"]
d = []
for key in reversed(keys):
   d = {key: d}

print(d)

Upvotes: 1

Views: 80

Answers (4)

cdlane
cdlane

Reputation: 41925

I agree with @Ajax1234 that this problem has a recursive flavor to it but I think it can be done much simpler code than his solution:

keys = ["key1", "key2", "key3"]

def nest(keys, value):
    key, *rest = keys

    if rest:
        value = nest(rest, value)

    return {key: value}

print(nest(keys, []))

Upvotes: 1

damisan
damisan

Reputation: 1047

After an edit made by the OP, the solution is now a one-liner:

result = reduce(lambda obj, key: {key: obj}, reversed(keys), [])
# {'key1': {'key2': {'key3': []}}}

Or with some functional programming:

from functools import reduce
keys = ["key1", "key2", "key3"]
result = reduce((lambda obj, key: {key: obj}), reversed(keys), dict())
print(result)
# {'key1': {'key2': {'key3': {}}}}

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71471

You can use recursion:

def get_dictionary(s, d):
   if not s[1:]:
      return {s[0]:d}
   else:
      if not d:
          return get_dictionary(s[1:], {s[0]:[]})
      else:
          return get_dictionary(s[1:], {s[0]:d})


print(get_dictionary(["key1", "key2", "key3"][::-1], {}))

Output:

{'key1': {'key2': {'key3': []}}}

Upvotes: 0

wim
wim

Reputation: 363486

Just a simple for-loop should do the trick

>>> d = {}
>>> for k in reversed(keys):
...     d = {k: d}
...     
>>> d
{'key1': {'key2': {'key3': {}}}}

(edit: OP changed the question after posting) Should you want a list as initial value, just change the first assignment:

>>> d = []
>>> for k in reversed(keys):
...     d = {k: d}
...     
>>> d
{'key1': {'key2': {'key3': []}}}

Upvotes: 7

Related Questions