On the question of a dictionary operation in python, separated by condition

the data obtained from the database is such a dictionary

{
    "q_1": 9, "q_2": 12, "q3": 22, "q4": 2, "q5": 6,
    "w_1": 9, "w_2": 12, "w_3": 22, "w_4": 2, "w_5": 6,
    "e_1": 9, "e_2": 12, "e_3": 22, "e_4": 2, "e_5": 6,
    "r_1": 9, "r_2": 12, "r_3": 22, "r_4": 2, "r_5": 6
}

how to divide it into this shape

{
    "q": {"q_1": 9, "q_2": 12, "q3": 22, "q4": 2, "q5": 6},
    "w": {"w_1": 9, "w_2": 12, "w_3": 22, "w_4": 2, "w_5": 6},
    ...
}

now I do it through for. Is there any easy and convenient way to do it? Thank you

Mar.03,2021

you can use itertools.groupby , refer to this article: https://codeshelper.com/a/11.

from itertools import groupby
d = {
    'q_1': 9, 'q_2': 12, 'q3': 22, 'q4': 2, 'q5': 6,
    'w_1': 9, 'w_2': 12, 'w_3': 22, 'w_4': 2, 'w_5': 6,
    'e_1': 9, 'e_2': 12, 'e_3': 22, 'e_4': 2, 'e_5': 6,
    'r_1': 9, 'r_2': 12, 'r_3': 22, 'r_4': 2, 'r_5': 6
}

new_dict = dict()
items = sorted(d.items())
for key, group in groupby(items, key=lambda x: x[0][0]):
    new_dict[key] = dict(group)
print(new_dict)
Menu