简体   繁体   中英

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.

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.

Each form in the dict has associated the string: form-number, I would like to create a dictionary for each form.

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?

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

[{'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

[{'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&'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM