我需要提交一个如下所示的formdata:
evt: 2001
evt: 1024001
src: mstrWeb.my.fbb.fb.2001
src: mstrWeb.my.fbb.1024001
当我创建python3 dict
时:
Dict = {'evt': '2001',
'evt': '1024001',
'src': 'mstrWeb.my.fbb.fb.2001',
'src': 'mstrWeb.my.fbb.1024001'}
按顺序删除重复的键。我明白了:
>>> print (Dict)
{'evt': '1024001', 'src': 'mstrWeb.my.fbb.1024001'}
有什么方法可以让我的Dict中的重复键完整无缺?
答案 0 :(得分:1)
Python dicts具有唯一键。没有绕过那个。
一种方法可能是在Python中创建defaultdict
列表,然后在表单代码中使用jinga for
循环来迭代dict的值。
或者,如果您能够发送json
字符串,this workaround for handling duplicate keys可能有所帮助:
<强>鉴于强>
data = [
("evt", "2001"),
("evt", "1024001"),
("src", "mstrWeb.my.fbb.fb.2001"),
("src", "mstrWeb.my.fbb.1024001")
]
<强>代码强>
class Container(dict):
"""Overload the items method to retain duplicate keys."""
def __init__(self, items):
self[""] = ""
self._items = items
def items(self):
return self._items
json.dumps(Container(data))
# '{"evt": "2001", "evt": "1024001", "src": "mstrWeb.my.fbb.fb.2001", "src": "mstrWeb.my.fbb.1024001"}'
答案 1 :(得分:0)
这对我有用,我从这里开始:Link
class person(object):
def __init__(self,name):
self.name = name
# As it would print for a user
def __str__(self):
return self.name
# As it would print for a debugging person
def __repr__(self):
return "'"+self.name+"'"
Dict = {person('evt'): '2001',
person('evt'): '1024001',
person('src'): 'mstrWeb.my.fbb.fb.2001',
person('src'): 'mstrWeb.my.fbb.1024001'}
print (Dict) #outputs
{'evt': '2001', 'evt': '1024001', 'src': 'mstrWeb.my.fbb.fb.2001', 'src': 'mstrWeb.my.fbb.1024001'}