[英]Python Split a dict into a list of dicts
When I get a request.POST
in my backend I would to create a dictionary for each form.当我在后端收到
request.POST
时,我会为每个表单创建一个字典。
Currently I have managed to pass the request.POST (QueryDict) to dict via request.POST.dict()
as I have seen in some StackOverflow question, however I still have to convert this dictionary to a list of dictionaries and I don't know how.目前我已经设法通过
request.POST.dict()
() 将 request.POST (QueryDict) 传递给 dict,正如我在一些 StackOverflow 问题中看到的那样,但是我仍然必须将此字典转换为字典列表,但我没有知识。
Each form in the dict has associated the string: form-number, I would like to create a dictionary for each form.字典中的每个表单都关联了字符串:form-number,我想为每个表单创建一个字典。
Current dict (simplified example):当前字典(简化示例):
{'form-0-a': 'MIE0158', 'form-0-b': 'ABHD12', 'form-0-jief': 'JUGI&', 'form-1-a': 'MIE0158', 'form-1-b': 'ABHD12', 'form-1-jief': 'JUGI&', 'form-2-a': 'MIE0158', 'form-2-b': 'ABHD12', 'form-2-jief': 'JUGI&'}
Desired list of dicts:所需的字典列表:
[{'form-0-a': 'MIE0158', 'form-0-b': 'ABHD12', 'form-0-jief': 'JUGI&'}, {'form-1-a': 'MIE0158', 'form-1-b': 'ABHD12', 'form-1-jief': 'JUGI&'}, {'form-2-a': 'MIE0158', 'form-2-b': 'ABHD12', 'form-2-jief': 'JUGI&'}]
I am not familiar with Python so I was wondering what would be the most pythonic way to do this?我不熟悉 Python 所以我想知道最pythonic的方法是什么?
You can create a dictionary like so.您可以像这样创建字典。
dict_1= {'form-0-a': 'MIE0158', 'form-0-b': 'ABHD12', 'form-0-jief': 'JUGI&', 'form-1-a': 'MIE0158', 'form-1-b': 'ABHD12', 'form-1-jief': 'JUGI&', 'form-2-a': 'MIE0158', 'form-2-b': 'ABHD12', 'form-2-jief': 'JUGI&'}
res = {}
for key, value in dict_1.items():
key_ = key.rsplit('-', 1)[0]
res.setdefault(key_, {}).update({key:value})
print(list(res.values()))
Output Output
[{'form-0-a': 'MIE0158', 'form-0-b': 'ABHD12', 'form-0-jief': 'JUGI&'}, {'form-1-a': 'MIE0158', 'form-1-b': 'ABHD12', 'form-1-jief': 'JUGI&'}, {'form-2-a': 'MIE0158', 'form-2-b': 'ABHD12', 'form-2-jief': 'JUGI&'}]
def test_function():
test = {'form-0-a': 'MIE0158', 'form-0-b': 'ABHD12', 'form-0-jief': 'JUGI&', 'form-1-a': 'MIE0158', 'form-1-b': 'ABHD12',
'form-1-jief': 'JUGI&', 'form-2-a': 'MIE0158', 'form-2-b': 'ABHD12', 'form-2-jief': 'JUGI&'}
form_num = 0
new_dict = {}
new_list = []
for num, item in enumerate(test):
if int(item[5]) == form_num:
new_dict[item] = test[item]
else:
form_num = int(item[5])
new_list.append(new_dict.copy())
new_dict = {}
new_list.append(new_dict.copy())
print(new_list)
if __name__ == '__main__':
test_function()
output output
[{'form-0-a': 'MIE0158', 'form-0-b': 'ABHD12', 'form-0-jief': 'JUGI&'}, {'form-1-a': 'MIE0158', 'form-1-b': 'ABHD12', 'form-1-jief': 'JUGI&'}, {'form-2-a': 'MIE0158', 'form-2-b': 'ABHD12', 'form-2-jief': 'JUGI&'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.