Python Forum
Create Dynamic nested Dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Dynamic nested Dictionaries
#7
I don't think there is a built-in way, but it can be done easily using DictFs. In the following example, I suppose that I have a directory foo/dummy on my disk:
def main2():
    import fs.copy
    with fs.open_fs('osfs://tmp') as root:
        dummy = root.opendir('dummy') # this is a fs.subfs.SubFS
        target = DictFs()
        fs.copy.copy_dir(dummy, '', target, 'dummy')
        mydict = target.as_dict()['dummy']
        print(mydict)

if __name__ == '__main__':
    main2()
Output:
{'Boston': {'Restaurants': {'Spoke Wine Bar': {'ZipCode': b'02144', 'Addr1': b'89 holland St', 'Phone': b'617-718-9463', 'City': b'Sommerville'}, 'Highland Kitchen': {'ZipCode': b'02144', 'Addr1': b'150 Highland Ave', 'Phone': b'617-625-1131', 'City': b'Sommerville'}}}}
It gives me the idea to improve the as_dict() method by adding an optional path argument. Soon an improved version on the gist!

The great thing is that one can copy files and directory from one fs to another!


EDIT: I upgraded the dictfs gist. One can now use a path argument in as_dict(), for example cd.as_dict('Boston/Restaurants'). There are also new constructors from_fs() and from_dir(). They can be used to create a DictFS from a different filesystem (including fs.subfs.SubFS), for example
with fs.open_fs('osfs://tmp') as root:
    dfs = DictFs.from_dir(root, 'dummy')
    print(dfs.as_dict())
Remember however that DictFs is a first implementation. It is not at all optimized nor is it seriously tested. Also note that PyFileSystem has an implementation of a memory file system if that's what you need.
Reply


Messages In This Thread
Create Dynamic nested Dictionaries - by Larz60+ - Nov-23-2018, 04:06 AM
RE: Create Dynamic nested Dictionaries - by Larz60+ - Nov-24-2018, 11:15 AM
RE: Create Dynamic nested Dictionaries - by Larz60+ - Nov-25-2018, 02:37 PM
RE: Create Dynamic nested Dictionaries - by Larz60+ - Nov-25-2018, 05:07 PM
RE: Create Dynamic nested Dictionaries - by Gribouillis - Nov-25-2018, 06:52 PM
RE: Create Dynamic nested Dictionaries - by Larz60+ - Nov-25-2018, 07:54 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Dynamic Allocation of Nested Dictionaries Larz60+ 15 17,703 Oct-11-2016, 02:42 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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