lst = [{'272': '4', '273': '4', '274': '4', '275': '5'}]
dct = {}
for k, v in lst[0].items():
if dct.get(v) is None:
dct.update({v: [k]})
else:
dct[v].append(k)
Output:
{'4': ['272', '273', '274'], '5': ['275']}
I can also write a nested comprehension:
dct = {v: [k for (k, v1) in lst[0].items() if v1 == v]
for (k, v) in lst[0].items()}
Output is same:
{'4': ['272', '273', '274'], '5': ['275']}**
But can we try to acheive the same result by using a single for loop in the dict comprehension?