Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create HTTP-request data with {single key:multi values} [duplicate]

I need to send HTTP POST request with data as follow:

data = {'id[]': '1', 'id[]': '2', 'id[]': '3'}

Values list is actually unknown, but let it be values_list = ['1', '2', '3']

Of course if to try

for value in values_list:
    data["id[]"] = value

I get {'id[]': '3'} as key-value pair will be overwritten on each iteration...

I used this solution:

data = {}

class data_keys(object):
    def __init__(self, data_key):
        self.data_key = data_key

for value in values_list:
    data[data_keys('id[]')] = value

But my data looks like

{<__main__.data_keys object at 0x0000000004BAE518>: '2',
 <__main__.data_keys object at 0x0000000004BAED30>: '1',
 <__main__.data_keys object at 0x0000000004B9C748>: '3'}

What is wrong with my code? How else can I simply create dict with single key?

UPDATED

This how my HTTP request looks like:

requests.post(url, data={"id[]": '1', "id[]": '2', "id[]": '3'}, auth=HTTPBasicAuth(user_name, user_passw))

Title updated

like image 274
Andersson Avatar asked Aug 13 '26 12:08

Andersson


1 Answers

While you can hack dictionary keys in order to allow seemingly “equal” keys, this is probably not a good idea, as this relies on the implementation detail on how the key is transformed into a string. Furthermore, it will definitely cause confusion if you ever need to debug this situation.

A much easier and supported solution is actually built into the form data encode mechanism: You can simply pass a list of values:

data = {
    'id[]': ['1', '2', '3']
}

req = requests.get(url='http://www.example.com', params=data)
print(req.url) # 'http://www.example.com/?id%5B%5D=1&id%5B%5D=2&id%5B%5D=3'

So you can just pass your values_list directly into the dictionary and everything will work properly without having to hack anything.


And if you find yourself in a situation where you think such a dictionary does not work, you can also supply an iterable of two-tuples (first value being the key, second the value):

data = [
    ('id[]', '1'),
    ('id[]', '2'),
    ('id[]', '3')
]

req = requests.get(url='http://www.example.com', params=data)
print(req.url) # 'http://www.example.com/?id%5B%5D=1&id%5B%5D=2&id%5B%5D=3'
like image 56
poke Avatar answered Aug 16 '26 00:08

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!