I have some dictionaries which I want to map to equal format:
PARTS = [{"part": 23, "subparts": [{"subpart": 1, "image": "first"},
{"subpart": 3, "image": "third"},
{"subpart": 5, "image": "fifth"}]},
{"part": 12, "subparts": [{"subpart": 4, "image": "FOURTH"},
{"subpart": 3, "image": "THIRD"},
{"subpart": 5, "image": "FIFTH"}]} ..]
I want to reorder the dict in a way that it looks like this:
PARTS_REORDERD = {"part": 23,
"subpart_1": {"image": "first"},
"subpart_2": {"image": None},
"subpart_3": {"image": "third"},
"subpart_4": {"image": None},
"subpart_5": {"image": "fifth"},
},
{
"part": 12,
"subpart_1": {"image": None},
"subpart_2": {"image": None},
"subpart_3": {"image": "THIRD"},
"subpart_4": {"image": "FOURTH"},
"subpart_5": {"image": "FIFTH"},
}
I have a working approach, which I dislike a lot because I think it is not very readable after not looking at the code for some time:
for i in PARTS:
PART = {}
PART["part"] = i["part"]
SUBPARTS = sorted(i["subparts"], key = lambda k: k["subpart"])
for j in range(1, 6):
try:
PART[f"subpart_{j}"] = next({"image": p["image"]} for p in SUBPARTS if p["subpart"] == j)
except Exception as E:
PART[f"subpart_{j}"] = {"image": None}
print(PART)
results in:
{'part': 23, 'subpart_1': {'image': 'first'},
'subpart_2': {'image': None},
'subpart_3': {'image': 'third.'},
'subpart_4': {'image': None},
'subpart_5': {'image': "fifth"}},
{'part': 12, 'subpart_1': {'image': None},
'subpart_2': {'image': None},
'subpart_3': {'image': 'THIRD'},
'subpart_4': {'image': 'FOURTH'},
'subpart_5': {'image': "FIFTH"}}
I tried a couple of things especially to avoid the next(). But maybe there is an easier to read approach at all?