Python program to convert URL Parameters to Dictionary items
Given URL Parameters string, convert to dictionary items.
Input : test_str = ‘gfg=4&is;=5’
Output : {‘gfg’: [‘4’], ‘is’: [‘5’]}
Explanation : gfg’s value is 4.Input : test_str = ‘gfg=4’
Output : {‘gfg’: [‘4’]}
Explanation : gfg’s value is 4 as param.
Method #1 : Using urllib.parse.parse_qs()
This is default inbuilt function which performs this task, it parses and the keys are formed from LHS of “=” and return list of values that are in RHS values for the parameters. Thus, import external urllib.parse(), to enable this to work.
Python3
# import moduleimport urllib.parse# initializing stringtest_str = 'gfg=4&is;=5&best;=yes'# printing original stringprint("The original string is : " + str(test_str))# parse_qs gets the Dictionary and value listres = urllib.parse.parse_qs(test_str)# printing resultprint("The parsed URL Params : " + str(res)) |
Method #2 : Using findall() + setdefault()
In this, we get all the parameters using findall(), and then assign keys and values using setdefault() and loop.
Python3
import re# initializing stringtest_str = 'gfg=4&is;=5&best;=yes'# printing original stringprint("The original string is : " + str(test_str))# getting all paramsparams = re.findall(r'([^=&]+)=([^=&]+)', test_str)# assigning keys with valuesres = dict()for key, val in params: res.setdefault(key, []).append(val)# printing resultprint("The parsed URL Params : " + str(res)) |
Method #3 : Using split()
Python3
#python program to convert#URL parameters to dictionary items# initializing stringtest_str = 'gfg=4&is;=5&best;=yes'# printing original stringprint("The original string is : " + str(test_str))# getting all paramsres = dict()x=test_str.split("&")for i in x: a,b=i.split("=") # assigning keys with values res[a]=[b]# printing resultprint("The parsed URL Params : " + str(res)) |
The original string is : gfg=4&is=5&best=yes
The parsed URL Params : {'gfg': ['4'], 'is': ['5'], 'best': ['yes']}

