Python Forum
Dynamic Allocation of Nested Dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamic Allocation of Nested Dictionaries
#16
Ok,

I tested (enough for current needs) this version, and will  be importing it into the project
where I decided I needed it, and if necessary, fix any new bugs that pop up and re-post.

Thanks all for contributions and suggestions.

from collections import defaultdict


class DynamicNestedDict(defaultdict):
    def __init__(self, *args, **kwargs):
        super(DynamicNestedDict, self).__init__(DynamicNestedDict, *args, **kwargs)

    def set_from_list(self, keylist, value):
        level = self
        for key in keylist[:-1]:
            level = level[key]
        level[keylist[-1]] = value

    def get_from_list(self, keylist):
        level = self
        for key in keylist[:-1]:
            level = level[key]
        return level[keylist[-1]]


def try_dynamic_nested_dict():
    keylist = ['bind', 'application level', 'binding']
    loc = [20, 96, 100, 101, 102, 104, 105, 115, 193, 434, 546]
    dd = DynamicNestedDict()
    dd.set_from_list(keylist, loc)
    result = dd.get_from_list(keylist)
    print("dd['bind']['application level']['binding']: {}".format(result))


if __name__ == '__main__':
    try_dynamic_nested_dict()


Messages In This Thread
RE: Dynamic Allocation of Nested Dictionaries - by Larz60+ - Oct-11-2016, 02:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create Dynamic nested Dictionaries Larz60+ 8 9,222 Nov-26-2018, 12:58 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020