Issue
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'}
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'}
Answered By - Sreeram TP
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.