Python program to convert URL Parameters to Dictionary items


Python's implementation of a data structure known more commonly as an associative array is a dictionary. A dictionary is made up of a group of key-value pairs. Each key-value combination corresponds to a key and its corresponding value.

In this article, we will learn a python program to convert URL parameters to dictionary items.

Methods Used

The following are the various methods to accomplish this task −

  • Using urllib.parse.parse_qs() function

  • Using setdefault() and re.findall() functions

  • Using split() function

Example

Assuming we have taken an input string with URL parameters, we convert this query string to the dictionary of items as shown below.

Input

'tutorials=9&Point=3&Website=2&is=1&best=Yes'

Output

The parsed URL Params of an input string:  {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

Using urllib.parse.parse_qs() function

In this method, we are going to use the following default inbuilt function to accomplishes this task;

urllib.parse.parse_qs() function:

it parses, and the keys are created from the LHS of "=", and it returns a list of values that are in the RHS values for the arguments. To make this work, import external urllib.parse().

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the import keyword to import the urllib.parse module.

  • Create a variable to store the input string.

  • Print the input string.

  • Use the urllib.parse.parse_qs() function by passing the input string as an argument to it.

  • Here the above step converts the given URL parameter(query string) to the dictionary of the items.

  • Print the resultant parsed URLs params of an input string

Example

The following program returns dictionary items of the given URL parameter string using urllib.parse.parse_qs() function –

# importing urllib.parse module
import urllib.parse
# input string
inputString = 'tutorials=9&Point=3&Website=2&is=1&best=Yes'
# printing input string
print("Input String:", inputString)
# Pass the input string to parse_qs(query string) to convert to dictionary
resultParams = urllib.parse.parse_qs(inputString)
# printing resultant parsed URLs params of an input string 
print("The parsed URL Params of an input string: ", resultParams)

Output

Input String: tutorials=9&Point=3&Website=2&is=1&best=Yes
The parsed URL Params of an input string:  {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

Using setdefault() and re.findall() functions

re.findall() function − The all non-overlapping matches of pattern in string, as a list of strings is returned by the findall() function. The string is scanned from left to right, and matches are returned in the order they were found.

setdefault() method

The value of the item with the given key is returned by the setdefault() method.

If the key does not already exist, insert it with the given value.

Syntax

dictionary.setdefault(keyname, value)

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the import keyword to import the re(regex) module.

  • Use the findall() function of re module to get getting all params from the input string using the regex pattern by passing the regex pattern, string as arguments to it.

  • Create a new empty dictionary for storing resultant parsed URLs of the input string

  • Use the for loop to traverse through the key, values of the above-all params dictionary.

  • Set the value of the dictionary as a list using the [] operator and setdefault function.

  • Append this value to the dictionary using the append() function.

  • Print the resultant parsed URLs params of the input string.

Example

The following program returns dictionary items of the given URL parameter string using Using setdefault() and re.findall() functions –

# importing re module
import re
# input string
inputString = 'tutorials=9&Point=3&Website=2&is=1&best=Yes'
# printing input string
print("Input String:", inputString)
# getting all params from input string using regex pattern
all_params = re.findall(r'([^=&]+)=([^=&]+)', inputString)
# Creating a new dictionary to store the URL Parameters as dictionary items
resultantDict = dict()
# traversing through the key, values of above all_params dictionary
for k, v in all_params:
  # Set the value of the dictionary as a list using the [] operator and setdefault function
  # Then append this value to the dictionary 
    resultantDict.setdefault(k, []).append(v)
# printing resultant parsed urls params of input string
print("The parsed urls params of input string:", resultantDict)

Output

On executing, the above program will generate the following output –

Input String: tutorials=9&Point=3&Website=2&is=1&best=Yes
The parsed URLs params of an input string: {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

Using the split() function

In this method we are goint to us the split method to covert the URL parameters to dictionary items.

Syntax

split():

splits a string into a list. We can define the separator; the default separator is any whitespace.

Example

The following program returns dictionary items of the given URL parameter string using the split() function –

# input string
inputString = 'tutorials=9&Point=3&Website=2&is=1&best=Yes'
# printing input string
print("Input String:", inputString)
# creating an empty dictionary for storing all params
resultantDict = dict()
# splitting input string based on & separator
splittedList = inputString.split("&")
# Traverse in the split list using the for loop
for k in splittedList:
  # Split the list again with "=" separator and store the key and value separately
	p,q=k.split("=")
	# Assign the above key with the list value to the result Dictionary
	resultantDict[p]=[q]
# printing resultant parsed URLs params of the input string 
print("The parsed URLs params of input string:", resultantDict)

Output

On executing, the above program will generate the following output –

Input String: tutorials=9&Point=3&Website=2&is=1&best=Yes
The parsed URLs params of an input string: {'tutorials': ['9'], 'Point': ['3'], 'Website': ['2'], 'is': ['1'], 'best': ['Yes']}

Conclusion

In this article, we have learned how to convert URL Parameters to Dictionary items using 3 different methods. Using the regex.findall() function, we learned how to split a given string using regex. We learned how to use the setdefault() function to change the dictionary's value to any default value.

Updated on: 18-Aug-2023

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements