Given is a string:
'search=hello+world&status=something&cache=false'
How do I pass parameters and values from that string to a payload dictionary given that I'm not sure what parameters I will always get from the string in order to use it in requests.get()?
requests.get(url, params=payload, headers=headers)
you can give as follows
url = url + '?'+ your_parm_string r = requests.get(url, headers=headers)
string = 'search=hello+world&status=something&cache=false'
params = string.split('&')
payload = {}
for params in param:
p = param.split('=')
payload[p[0]] = p[1]
print(payload)
{'search': 'hello+world', 'status': 'something', 'cache': 'false'}
Use a dict
comprehension :
def split_params(param_string):
return {param: value for param, value in (pair.split('=') for pair in param_string.split('&'))}
split_params('search=hello+world&status=something&cache=false')
Output:
{'search': 'hello+world', 'status': 'something', 'cache': 'false'}
This is based off the observation that each param-value pair is separated externally by an &
and internally by an =
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.