Steve Litt via plug on 3 Jul 2021 11:03:44 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Python nested dict data structure


Carlos M. Fernández via plug said on Fri, 2 Jul 2021 17:19:32 -0400

>What prevents you from doing this?:
>
>>>> d = dict()
>>>> d  
>{}
>>>> company = "Acme, Inc."
>>>> company  
>'Acme, Inc.'
>>>> d[company] = {"region": "US", "counter": 1}
>>>> d  
>{'Acme, Inc.': {'region': 'US', 'counter': 1}}
>>>> d[company]["counter"] += 1
>>>> d  
>{'Acme, Inc.': {'region': 'US', 'counter': 2}}

The preceding is how I've always done it. I'm not sure why big data
structures in Python would be cumbersome or difficult to comprehend.
It's only necessary to remember that any data structure can be made
from arrays (Python lists) and sets of key/value pairs (Python dicts).
Just build them up.

Another data point: Python complex structures and JSON convert
losslessly to each other. Perhaps the OP (Original Poster) would want to
build his initial structure in JSON, and then convert to a structure.
IIRC Python's JSON library is part of Python's standard libraries.

Another technique I use is to create sub-dicts and sub-sub-dicts, etc,
and when each is complete, bolt it onto the next higher level. More
understandable that way.


SteveT

Steve Litt 
Spring 2021 featured book: Troubleshooting Techniques of the Successful
Technologist http://www.troubleshooters.com/techniques
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug