In order to make your data_keys
class do what you want you need to give it an appropriate __repr__
or __str__
method. This will allow the class instances to be displayed in the desired fashion when you print the dict, or when some other code tries to serialize it.
Here's a short demo that uses the 3rd party requests module to build a URL. I've changed the class name to make it conform to the usual Python class naming convention. This code was tested on Python 2.6 and Python 3.6
from __future__ import print_function
import requests
class DataKey(object):
def __init__(self, data_key):
self.data_key = data_key
def __repr__(self):
return str(self.data_key)
data = {}
values_list = ['1', '2', '3']
for value in values_list:
data[DataKey('id[]')] = value
print(data)
req = requests.get(url='http://www.example.com', params=data)
print(req.url)
output
{id[]: '1', id[]: '2', id[]: '3'}
http://www.example.com/?id%5B%5D=1&id%5B%5D=2&id%5B%5D=3
Here's a more robust version inspired by Rogalski's answer that is acceptable to the json
module, .
from __future__ import print_function
import requests
import json
class DataKey(str):
def __init__(self, data_key):
self.data_key = data_key
def __repr__(self):
return str(self.data_key)
def __eq__(self, other):
return self is other
def __hash__(self):
return id(self)
data = {}
values_list = ['1', '2', '3']
for value in values_list:
data[DataKey('id[]')] = value
print(data)
req = requests.get(url='http://www.example.com', params=data)
print(req.url)
print(json.dumps(data))
output
{id[]: '3', id[]: '1', id[]: '2'}
http://www.example.com/?id%5B%5D=3&id%5B%5D=1&id%5B%5D=2
{"id[]": "3", "id[]": "1", "id[]": "2"}
As I mentioned in my comment on the question, this is weird, and creating dictionaries with multiple (pseudo)identical keys is really not a very useful thing to do. There will almost always be a far better approach, eg using a dict
of lists or tuples, or as in this case, an alternative way of supplying the data, as shown in Poke's answer.
However, I should mention that multiple identical keys are not prohibited in JSON objects, and so it may occasionally be necessary to deal with such JSON data. I'm not claiming that using one of these crazy dictionaries is a good way to do that but it is a possibility...