As the title suggest I am trying to urlencode using Ordered Dict in python
def url_replace(request, field, value, direction=""):
dict_ = request.GET.copy()
if field == "order_by" and field in dict_.keys():
if dict_[field].startswith("-") and dict_[field].lstrip("-") == value:
dict_[field] = value
elif dict_[field].lstrip("-") == value:
dict_[field] = "-" value
else:
dict_[field] = direction value
else:
dict_[field] = direction str(value)
print("UNORDERED___________________")
print(dict_)
print(super(MultiValueDict, dict_).items())
print("ORDERED_____________")
print(OrderedDict(super(MultiValueDict, dict_).items()))
print(OrderedDict(dict_.items()))
return urlencode(OrderedDict(dict_.items()))
The output for the above code
UNORDERED___________________
<QueryDict: {'assigned_to_id': ['1', '2'], 'client_id': ['2', '1'], 'page': ['2']}>
dict_items([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])])
OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')])
ORDERED_____________
OrderedDict([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])])
OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')])
As you can see the assigned_to_id has only 2
in the end .
What I am expecting is a ordered dict with
OrderedDict([('assigned_to_id', '2'),('assigned_to_id', '1'), ('client_id', '1'), ('client_id', '2'),('page', '2')])
Maybe there might be a better approach for this, I am a bit new to python
My final aim is to return a dict with multiple keys or anything that can be used in urlencode
CodePudding user response:
When a sequence of two-element tuples is used as the query argument, the first element of each tuple is a key and the second is a value. The value element in itself can be a sequence and in that case, if the optional parameter
doseq
evaluates to True, individual key=value pairs separated by '&' are generated for each element of the value sequence for the key. The order of parameters in the encoded string will match the order of parameter tuples in the sequence.
Here is a simple example:
from urllib import parse
print(parse.urlencode({"a": [1, 2], "b": 1}, doseq=True))
# "a=1&a=2&b=1"