Python | Key-Value to URL Parameter Conversion
Last Updated :
04 Apr, 2023
Many times, while working in the web development domain, we can encounter a problem in which we require to set as URL parameters some of the key-value pairs we have, either in form of tuples, or a key and value list. Let’s discuss a solution for both cases.
Method #1: Using urllib.urlencode() ( with tuples ) The urlencode function is root function that can perform the task that we wish to achieve. In the case of tuples, we can just pass the tuples and encoder does the rest of conversion of string. Works only with Python2.
Python
import urllib
test_tuples = (( 'Gfg' , 1 ), ( 'is' , 2 ), ( 'best' , 3 ))
print ( "The original tuples are : " + str (test_tuples))
res = urllib.urlencode(test_tuples)
print ( "The URL parameter string is : " + str (res))
|
Output
The original tuples are : (('Gfg', 1), ('is', 2), ('best', 3))
The URL parameter string is : Gfg=1&is=2&best=3
Method #2: Using urllib.urlencode() ( with dictionary value list ) This method is when we have a dictionary key and many values corresponding to them as a potential candidate for being the URL parameter. In this case we perform this function. This also works with just Python2.
Python
import urllib
test_dict = { 'gfg' : [ 1 , 2 , 3 ]}
print ( "The original dictionary is : " + str (test_dict))
res = urllib.urlencode(test_dict, doseq = True )
print ( "The URL parameter string is : " + str (res))
|
Output
The original dictionary is : {'gfg': [1, 2, 3]}
The URL parameter string is : gfg=1&gfg=2&gfg=3
Method #3 : Using list(),map() and join() methods
Python3
test_tuples = (( 'gfg' , 1 ), ( 'is' , 2 ), ( 'best' , 3 ))
print ( "The original tuples are : " + str (test_tuples))
res = []
for i in test_tuples:
x = list ( map ( str ,i))
a = "=" .join(x)
res.append(a)
res = "&" .join(res)
print ( "The URL parameter string is : " + str (res))
|
Output
The original tuples are : (('gfg', 1), ('is', 2), ('best', 3))
The URL parameter string is : gfg=1&is=2&best=3
Method #4: Using reduce() function with lambda function
Step-by-step algorithm:
- Import the necessary modules.
- Initialize the tuples.
- Apply lambda function with reduce() function to convert tuples into URL parameter string.
a. Map the key-value pairs of each tuple into a string with ‘=’ in between.
b. Join the list of mapped strings with ‘&’ separator using lambda function and reduce() function.
- Print the URL parameter string.
Python3
import urllib
from functools import reduce
test_tuples = (( 'Gfg' , 1 ), ( 'is' , 2 ), ( 'best' , 3 ))
print ( "The original tuples are : " + str (test_tuples))
res = reduce ( lambda x, y: str (x) + '&' + str (y), [ '=' .join( map ( str , tpl)) for tpl in test_tuples])
print ( "The URL parameter string is : " + str (res))
|
Output
The original tuples are : (('Gfg', 1), ('is', 2), ('best', 3))
The URL parameter string is : Gfg=1&is=2&best=3
Time Complexity: O(n) where n is the number of tuples.
Space Complexity: O(n) where n is the number of tuples.
Method #5: Using numpy:
Algorithm:
- Initialize the input tuple containing key-value pairs.
- Initialize an empty list ‘res’ to store the URL parameter string.
- Loop through each tuple in the input tuple list:
a. Convert each key-value pair to a list of strings.
b. Join the list with “=” delimiter to form the URL parameter.
c. Append the parameter to the ‘res’ list.
- Join the ‘res’ list with “&” delimiter to form the final URL parameter string.
- Print the final URL parameter string.
Python3
import numpy as np
test_tuples = (( 'gfg' , 1 ), ( 'is' , 2 ), ( 'best' , 3 ))
print ( "The original tuples are : " + str (test_tuples))
res = "&" .join(np.array( list ( map ( lambda i: "=" .join( list ( map ( str ,i))), test_tuples))))
print ( "The URL parameter string is : " + str (res))
|
Output:
The original tuples are : (('gfg', 1), ('is', 2), ('best', 3))
The URL parameter string is : gfg=1&is=2&best=3
Time complexity :
The time complexity of the for loop is O(n), where ‘n’ is the length of the input tuple.
The conversion of key-value pairs to list of strings takes constant time, and joining the list with “=” delimiter also takes constant time.
The join operation to combine the list of URL parameters with “&” delimiter also takes O(n) time.
Therefore, the overall time complexity of the algorithm is O(n).
Auxiliary Space :
The space complexity of the algorithm is O(n), as we are storing each URL parameter in a separate list, and then joining all the parameters to form the final string.
Similar Reads
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
3 min read
Convert byte string Key:Value Pair of Dictionary to String - Python
In Python, dictionary keys and values are often stored as byte strings when working with binary data or certain encoding formats, we may need to convert the byte strings into regular strings. For example, given a dictionary {b'key1': b'value1', b'key2': b'value2'}, we might want to convert it to {'k
3 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
6 min read
Convert key-value pair comma separated string into dictionary - Python
In Python, we might have a string containing key-value pairs separated by commas, where the key and value are separated by a colon (e.g., "a:1,b:2,c:3"). The task is to convert this string into a dictionary where each key-value pair is represented properly. Let's explore different ways to achieve th
3 min read
Iterate Through Dictionary Keys And Values In Python
In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionar
2 min read
Python Print Dictionary Keys and Values
When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
2 min read
How to Print Dictionary Keys in Python
We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
2 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Get the File Extension from a URL in Python
Handling URLs in Python often involves extracting valuable information, such as file extensions, from the URL strings. However, this task requires careful consideration to ensure the safety and accuracy of the extracted data. In this article, we will explore four approaches to safely get the file ex
2 min read
Convert String to JSON Object - Python
The goal is to convert a JSON string into a Python dictionary, allowing easy access and manipulation of the data. For example, a JSON string like {"name": "John", "age": 30, "city": "New York"} can be converted into a Python dictionary, {'name': 'John', 'age': 30, 'city': 'New York'}, which allows y
2 min read