Python Forum
Create Dynamic nested Dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Dynamic nested Dictionaries
#4
Larz60+ Wrote:I am curious if os now uses PyFilesystem as there are new commands like os.fspath that use the fs prefix.
No Python itself doesn't depend on a third party module such as PyFileSystem. The role of PyFileSystem is to offer a unified API for different objects, so that the same code can be used in different contexts. Consider a slightly better version of the above code
from dictfs import DictFs

def fill(root):
    d = root.makedirs('Boston/Restaurants/Spoke Wine Bar')
    d.settext('Addr1', '89 Holland St')
    d.settext('City', 'Sommerville')
    d.settext('ZipCode', '02144')
    d.settext('Phone', '617-718-9463')
    d = root.makedirs('Boston/Restaurants/Highland Kitchen')
    d.settext('Addr1', '150 Highland Ave')
    d.settext('City', 'Sommerville')
    d.settext('ZipCode', '02144')
    d.settext('Phone', '617-625-1131')

def main():
    with DictFs() as root:
        fill(root)
        root.tree()

if __name__ == '__main__':
    main()
Output:
└── Boston └── Restaurants ├── Highland Kitchen │ ├── Addr1 │ ├── City │ ├── Phone │ └── ZipCode └── Spoke Wine Bar ├── Addr1 ├── City ├── Phone └── ZipCode
This code acts in memory on a python dictionary. I only need to replace DictFs() by fs.osfs.OSFS('/tmp') or fs.tarfs.TarFS('foo.tgz', write=True) to have the same code operate on a directory on disk or a gunzipped tar file. The same code can manipulate a remote FTP or dropbox hierarchy.

Of course, it may remain some filesystem specific code, for example if I want to call root.as_dict(), which is defined only for my DictFs class, but clearly, using the unified API, it would be quite easy to define a function as_dict that would apply to any of these filesystems. PyFileSystem is a great step towards code reusability!
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 Gribouillis - Nov-25-2018, 11:57 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 Larz60+ - Nov-25-2018, 07:54 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Dynamic Allocation of Nested Dictionaries Larz60+ 15 17,711 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