Trevor is using python requests with a website that takes duplicate keys to specify multiple values. The problem is, JSON and Python dictionaries do not allow duplicate keys, so only one of the keys makes it through.
## sample code
payload = {'fname': 'homer', 'lname': 'simpson'
, 'favefood': 'raw donuts'
, 'favefood': 'free donuts'
, 'favefood': 'cold donuts'
, 'favefood': 'hot donuts'
}
rtt = requests.post("http://httpbin.org/post", data=payload)
Web links:
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.
Why you can not have duplicate keys in a dictionary? You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary.
You can composite payload in this way:
payload = [
('fname', 'homer'), ('lname', 'simpson'),
('favefood', 'raw donuts'), ('favefood', 'free donuts'),
]
rtt = requests.post("http://httpbin.org/post", data=payload)
But if your case allows, I prefer POST a JSON with all 'favefoood' in a list:
payload = {'fname': 'homer', 'lname': 'simpson',
'favefood': ['raw donuts', 'free donuts']
}
# 'json' param is supported from requests v2.4.2
rtt = requests.post("http://httpbin.org/post", json=payload)
Or if JSON is not preferred, combine all 'favefood' into a string (choose separator carefully):
payload = {'fname': 'homer', 'lname': 'simpson',
'favefood': '|'.join(['raw donuts', 'free donuts']
}
rtt = requests.post("http://httpbin.org/post", data=payload)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With