Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython program to convert URL Parameters to Dictionary items

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 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']}

Method #4 : Using setdefault()

Approach

Using dictionary.setdefault() method

Algorithm

1. Split the input string into a list of key-value pairs using the split() method with the ‘&’ delimiter.
2. Create an empty dictionary to store the key-value pairs.
3. Iterate over the list of key-value pairs and split each item on the basis of ‘=’.
4. Add the key-value pairs to the dictionary using the setdefault() method. If the key does not exist, create a new key in the dictionary and initialize its value to an empty list. Then, append the value to this list.

Python3




# Python program to convert URL Parameters to Dictionary items
 
test_str = 'gfg=4&is=5'
 
# split the string on the basis of '&' and create a list of key-value pairs
temp_list = test_str.split('&')
 
# create an empty dictionary
res_dict = {}
 
# iterate over the key-value pairs and add them to the dictionary
for item in temp_list:
    key, val = item.split('='# split each item of the list on the basis of '='
    res_dict.setdefault(key, []).append(val)  # add key-value pair to dictionary
 
print(res_dict)


Output

{'gfg': ['4'], 'is': ['5']}

Time complexity: O(N) depends on the length of the input string and the number of key-value pairs in it. The split() method and the setdefault() method take linear time in the number of key-value pairs. where N is the number of key-value pairs in the input string.

Auxiliary Space: O(N),  depends on the number of key-value pairs in the input string. We create a dictionary to store the key-value pairs, and each key can have a list of values. where N is the number of key-value pairs in the input string.

METHOD 5:USING DEF AND FOR

APPROACH:

In this approach we append the value to the list associated with the key if the key is already in the dictionary, to handle the case where the same parameter appears multiple times in the URL with different values.

ALGORITHM:

1.Get the query string from the URL.
2.Split the query string into key-value pairs using the “&” character as a delimiter.
3Create an empty dictionary to store the key-value pairs.
4terate over each key-value pair:
a. Split the pair on the “=” character to get the key and value.
b. If the key already exists in the dictionary, append the value to the list associated with the key. Otherwise, create a new key-value pair in the 5.dictionary with the key and value.

Python3




def url_params_to_dict(url):
    # Get the query string from the URL
    query_string = url.split("?")[-1]
     
    # Split the query string into key-value pairs
    key_value_pairs = query_string.split("&")
     
    # Create a dictionary to store the key-value pairs
    params_dict = {}
     
    # Iterate over the key-value pairs and add them to the dictionary
    for pair in key_value_pairs:
        key, value = pair.split("=")
        if key in params_dict:
            params_dict[key].append(value)
        else:
            params_dict[key] = [value]
     
    return params_dict
 
# Example usage
params_dict = url_params_to_dict(url)
print(params_dict)


Output

{'gfg': ['4'], 'is': ['5'], 'best': ['yes']}

The time complexity of the url_params_to_dict function is O(n), where n is the length of the query string. 

The auxiliary space is also O(n), because we need to store the key-value pairs in a dictionary

RELATED ARTICLES

Most Popular

Recent Comments