The Wayback Machine - https://web.archive.org/web/20221001060218/https://www.geeksforgeeks.org/python-program-to-convert-url-parameters-to-dictionary-items/
Skip to content
Related Articles

Related Articles

Python program to convert URL Parameters to Dictionary items

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Jun, 2022
View Discussion
Improve Article
Save Article

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 module
import urllib.parse
 
# initializing string
test_str = 'gfg=4&is;=5&best;=yes'
 
# printing original string
print("The original string is : " + str(test_str))
 
# parse_qs gets the Dictionary and value list
res = urllib.parse.parse_qs(test_str)
 
# printing result
print("The parsed URL Params : " + str(res))

OutputThe original string is : gfg=4&is;=5&best;=yes The parsed URL Params : {‘gfg’: [‘4’], ‘is’: [‘5’], ‘best’: [‘yes’]}

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 string
test_str = 'gfg=4&is;=5&best;=yes'
 
# printing original string
print("The original string is : " + str(test_str))
 
# getting all params
params = re.findall(r'([^=&]+)=([^=&]+)', test_str)
 
# assigning keys with values
res = dict()
for key, val in params:
   
    res.setdefault(key, []).append(val)
 
# printing result
print("The parsed URL Params : " + str(res))

OutputThe original string is : gfg=4&is;=5&best;=yes The parsed URL Params : {‘gfg’: [‘4’], ‘is’: [‘5’], ‘best’: [‘yes’]}

Method #3 : Using split()

Python3




#python program to convert
#URL parameters to dictionary items
# initializing string
test_str = 'gfg=4&is;=5&best;=yes'
 
# printing original string
print("The original string is : " + str(test_str))
 
# getting all params
res = dict()
x=test_str.split("&")
for i in x:
    a,b=i.split("=")
    # assigning keys with values
    res[a]=[b]
# printing result
print("The parsed URL Params : " + str(res))

Output

The original string is : gfg=4&is=5&best=yes
The parsed URL Params : {'gfg': ['4'], 'is': ['5'], 'best': ['yes']}

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!