Python convert path to dict

2024/7/7 6:06:45

I have a list of paths that need to be converted to a dict

["/company/accounts/account1/accountId=11111","/company/accounts/account1/accountName=testacc","/company/accounts/account1/environment=test","/company/accounts/account2/accountId=22222","/company/accounts/account2/accountName=stageacc","/company/accounts/account2/environment=stage","/program/releases/program1/stage/version=1.1","/program/releases/program1/stage/date=2021-02-01","/program/releases/program1/prod/version=1.0","/program/releases/program1/prod/date=2021-01-15",
]

Here is what it should look like:

{"company": {"accounts": {"account1": {"accountId": 11111,"accountName": "testacc","environment": "test"},"account2": {"accountId": 22222,"accountName": "stageacc","environment": "stage"}}},"program": {"releases": {"program1": {"stage": {"version": "1.1","date": "2021-02-01"},"prod": {"version": "1.0","date": "2021-01-15"}}}}
}

I am trying to solve this iteratively but I can't seem to get it to work. Not sure what is the right approach here when it comes to nested dictionaries.

Here is my code:

class Deserialize:def __init__(self):self.obj = {}def deserialize_iteratively(self, paths):def helper(path):path_elements = path.split('/')for e in path_elements[::-1]:if "=" in e:k,v = e.split("=")self.obj[k] = velse:tmp = {}tmp[e] = self.objself.obj = tmpreturn self.objfor path in paths:helper(path)return self.obj

And the erroneous output this generates with first two paths:

{'': {'company': {'accounts': {'account1': {'': {'company': {'accounts': {'account1': {'accountId': '11111'}}}},'accountName': 'testacc'}}}}}
Answer

You'll want to use .setdefault() to create the dicts as you dig through the path.

from pprint import pprints = ["/company/accounts/account1/accountId=11111","/company/accounts/account1/accountName=testacc","/company/accounts/account1/environment=test","/company/accounts/account2/accountId=22222","/company/accounts/account2/accountName=stageacc","/company/accounts/account2/environment=stage","/program/releases/program1/stage/version=1.1","/program/releases/program1/stage/date=2021-02-01","/program/releases/program1/prod/version=1.0","/program/releases/program1/prod/date=2021-01-15",
]root = {}for path in s:# separate by slashes, disregarding the first `/`path = path.lstrip("/").split("/")# pop off the last key-value componentkey, _, val = path.pop(-1).partition("=")# find the target dict starting from the roottarget_dict = rootfor component in path:target_dict = target_dict.setdefault(component, {})# assign key-valuetarget_dict[key] = valpprint(root)

Outputs:

{'company': {'accounts': {'account1': {'accountId': '11111','accountName': 'testacc','environment': 'test'},'account2': {'accountId': '22222','accountName': 'stageacc','environment': 'stage'}}},'program': {'releases': {'program1': {'prod': {'date': '2021-01-15','version': '1.0'},'stage': {'date': '2021-02-01','version': '1.1'}}}}}
https://en.xdnf.cn/q/119641.html

Related Q&A

Python: How to download images with the URLs in the excel and replace the URLs with the pictures?

As shown in the below picture,theres an excel sheet and about 2,000 URLs of cover images in the F column. What I want to do is that downloading the pictures with the URLs and replace the URL with the…

I cant figure out pip tensorrt line 17 error

I couldnt install it in any way, I wonder what could be the cause of the error. I installed C++ and other necessary stuff I am using windows 11 I installed pip install nvidia-pyindex with no problem. S…

Extracting specific values for a header in different lines using regex

I have text string which has multiple lines and each line has mix of characters/numbers and spaces etc. Here is how a couple lines look like:WEIGHT VOLUME CHA…

Creating a function to process through a .txt file of student grades

Can someone help...My driver file is here:from functions import process_marks def main():try:f = open(argv[1])except FileNotFoundError:print("\nFile ", argv[1], "is not available")e…

Python Reddit PRAW get top week. How to change limit?

I have been familiarising myself with PRAW for reddit. I am trying to get the top x posts for the week, however I am having trouble changing the limit for the "top" method. The documentatio…

I want to convert string 1F to hex 1F in Python, what should I do?

num="1F" nm="1" nm1="2" hex(num)^hex(nm)^hex(nm1)I wrote it like the code above, but hex doesnt work properly. I want to convert the string to hexadecimal, and I want an x…

How to call a function in a Django template?

I have a function on my views.py file that connects to a mail server and then appends to my Django model the email addresses of the recipients. The script works good. In Django, Im displaying the model…

Remove duplicates from json file matching against multiple keys

Original Post = Remove duplicates from json dataThis is only my second post. I didnt have enough points to comment my question on the original post...So here I am.Andy Hayden makes a great point - &quo…

Merging CSVs with similar name python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 8…

urllib.error.HTTPError: HTTP Error 403: Forbidden

I get the error "urllib.error.HTTPError: HTTP Error 403: Forbidden" when scraping certain pages, and understand that adding something like hdr = {"User-Agent: Mozilla/5.0"} to the h…