Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse URL parameter and create a dictionary

I want to have the URL parameters as a "real" dict. How can I achieve that? I don’t want to use params.split() multiple times.

from urllib.parse import urlparse

url = 'http://nohost.com?params=depth:1,width:500,size:small'

the_url = urlparse(url)
url_part, params = the_url.path, the_url.query

print(params)  # params=depth:1,width:500,size:small

At the end of the day I want to have a real dictionary from the URL parameters

params = {'depth': 1, 'width': 500, 'size': 'small'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to parse the params yourselves. As @jonrsharpe pointed out in the comments, you can choose to use parse_qs to get a dict of list after parsing the output of urlparse and then pretty much implement the parsing logic.

Something like this,

from urllib.parse import urlparse, parse_qs

url = 'http://nohost.com?params=depth:1,width:500,size:small'

url_parts = urlparse(url)
parsed_str = parse_qs(url_parts.query)['params'][0]

params_dict = {
    key: int(value) if value.isdigit() else value
    for key, value in (pair.split(':') for pair in parsed_str.split(','))
}


print(params_dict) # {'depth': 1, 'width': 500, 'size': 'small'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading