The Wayback Machine - https://web.archive.org/web/20240924145135/https://www.geeksforgeeks.org/python-program-to-convert-url-parameters-to-dictionary-items/
Open In App

Python program to convert URL Parameters to Dictionary items

Last Updated : 07 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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



Similar Reads

How to Add URL Parameters to Django Template URL Tag?
When building a Django application, it's common to construct URLs dynamically, especially when dealing with views that require specific parameters. The Django template language provides the {% url %} template tag to create URLs by reversing the URL patterns defined in the urls.py file. This tag becomes especially useful when we need to pass additio
4 min read
Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python | Split URL from Query Parameters
Sometimes, while web development, we can come across a task in which we may require to perform a split of query parameters from URLs which is done by '?' character. This has application over web development as well as other domains which involve URLs. Lets discuss certain ways in which this task can be performed. Method #1 : Using split() This is o
6 min read
Python - Convert dictionary items to values
Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let's discuss certain ways in which this task can be
3 min read
How to Handle Missing Parameters in URL with Flask
In this article, we will discuss how to handle missing parameters in URLs with Flask. It is a web framework that offers libraries for creating simple web applications in Python. In Flask, URL parameters, commonly referred to as "query strings," you can organize extra information for a certain URL. Parameters are added to the end of a URL after a ‘?
4 min read
Python program to find the sum of all items in a dictionary
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary. Examples: Input : {'a': 100, 'b':200, 'c':300}Output : 600 Input : {'x': 25, 'y':18, 'z':45}Output : 88 Method #1: Using Inbuilt sum() Function Use the sum function to find the sum of dictionary values. C/C++ Code # Python3 Program to find sum of #
6 min read
Python program to extract dictionary items for custom values
Given a dictionary, extract all the items that match given values in the list Example: Input : test_dict = {"Gfg" : 3, "is" : 5, "for" : 8, "Geeks" : 10, "Best" : 16 }, sub_list = [5, 4, 10, 20, 16, 8] Output : {'is': 5, 'Geeks': 10, 'Best': 16, "for" : 8} Explanation : All values matching list values extracted along with keys. Input : test_dict =
4 min read
Python program to multiply all the items in a dictionary
Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5':1} Output: ans = 120 Input: dict = {'v1':10, 'v2'
2 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done in Python. Example Converting dictionary string to dictionary using json
5 min read
Comparing path() and url() (Deprecated) in Django for URL Routing
When building web applications with Django, URL routing is a fundamental concept that allows us to direct incoming HTTP requests to the appropriate view function or class. Django provides two primary functions for defining URL patterns: path() and re_path() (formerly url()). Although both are used for routing, they serve slightly different purposes
8 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Count number of items in a dictionary value that is a list
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or
5 min read
Python | Get items in sorted order from given dictionary
Given a dictionary, the task is to get all items from the dictionary in sorted order. Let's discuss different ways we can do this task. Method #1: Using sorted() C/C++ Code # Python code to demonstrate # to get sorted items from dictionary # initialising _dictionary ini_dict = {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} # printing iniial_diction
3 min read
Python | Get first K items in dictionary
While working with dictionaries, we can come across a problem in which we might have to get just some of the initial keys in dictionary. This problem can typically occur in cases of the web development domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using items() + list slicing To solve this problem, a combinatio
6 min read
Python | Type conversion of dictionary items
The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let's discuss certain ways in which this task can be performed. Method #1 :
6 min read
Python | Sort the items alphabetically from given dictionary
Given a dictionary, write a Python program to get the alphabetically sorted items from given dictionary and print it. Let’s see some ways we can do this task. Code #1: Using dict.items() C/C++ Code # Python program to sort the items alphabetically from given dictionary # initialising _dictionary dict = {'key2' : 'For', 'key3': 'IsGeeks', 'key1' : '
1 min read
Python - Frequency of unequal items in Dictionary
Sometimes, while working with Python, we can come across a problem in which we need to check for the unequal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let’s discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehension This particular task
5 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Let’s discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops is a naive brute force approach to perform this p
10 min read
Python - All possible items combination dictionary
Sometimes, while working with data, we can have a problem in which we are provided with sample data of key and value list and we require to construct actual data as all possible combination of keys and value list of similar size. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + set() The combination of above f
4 min read
Python - Sorted order Dictionary items pairing
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform reordering of dictionary items, to pair key and values in sorted order, smallest pairing to smallest value, largest to largest value and so on. This kind of application can occur in competitive domain and day-day programming. Lets discuss certain ways
3 min read
Python - Assign list items to Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign list elements as a new key in dictionary. This task can occur in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop The combination of above functions can be used to solve this proble
10 min read
Python - Extract dictionary items with List elements
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the items from dictionary that constitute all the elements from a list. This kind of problem can occur in domains such as competitive programming and web development. Let's discuss certain ways in which this task can be performed. Input : test_d
8 min read
Python - Remove K value items from dictionary nesting
Given dictionary with multiple nestings, remove all the keys with value K. Input : [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}}, {"is" : {"j" : 8, "k" : 10}}, {"Best" : {"i" : 16}}], K = 8 Output : [{'a': 5}, {'c': 9}, {'k': 10}, {'i': 16}] Explanation : All the keys with value 8, ("b", "j") has been removed. Input : [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}
4 min read
Python - Column Mapped Tuples to dictionary items
Given Tuple Matrix of length 2, map each column's element value with next column and construct dictionary keys. Input : test_list = [[(1, 4), (6, 3), (4, 7)], [(7, 3), (10, 14), (11, 22)]] Output : {1: 7, 4: 3, 6: 10, 3: 14, 4: 11, 7: 22} Explanation : 1 -> 7, 4 -> 3.., as in same column and indices. Input : test_list = [[(1, 4), (6, 3)], [(7
4 min read
Python - Append items at beginning of dictionary
Given a dictionary, append another dictionary at beginning of it. Input : test_dict = {"Gfg" : 5, "is" : 3, "best" : 10}, updict = {"pre1" : 4} Output : {'pre1': 4, 'Gfg': 5, 'is': 3, 'best': 10} Explanation : New dictionary updated at front of dictionary. Input : test_dict = {"Gfg" : 5}, updict = {"pre1" : 4} Output : {'pre1': 4, 'Gfg': 5} Explana
3 min read
Python - Dictionary items in value range
Given a range of values, extract all the items whose keys lie in a range of values. Input : {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}, i, j = 9, 12Output : {'best' : 9, 'geeks' : 11} Explanation : Keys within 9 and 11 range extracted. Input : {'Gfg' : 6, 'is' : 7, 'best' : 9, 'for' : 8, 'geeks' : 11}, i, j = 14, 18 Output : {} Expl
8 min read
Python - Extract Dictionary Items with Summation Greater than K
Given dictionary with value lists, extract all those items with values summing over K. Input : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]}, K = 10 Output : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]} Explanation : All elements
5 min read