Home > Blockchain >  One liner to restructure/nest a dictionary
One liner to restructure/nest a dictionary

Time:10-26

I'm wondering if in Python3 there is a one liner that can turn:

in_dict = {
    ("ID1", "TEXT_A"): "TIMESTAMP_X",
    ("ID1", "TEXT_B"): "TIMESTAMP_Y",
    ("ID2", "TEXT_C"): "TIMESTAMP_X",
    ("ID3", "TEXT_E"): "TIMESTAMP_Y",
}

into

out_dict = {
    "ID1": [
        {"TEXT_A": "TIMESTAMP_X"}, 
        {"TEXT_B": "TIMESTAMP_Y"}
    ],
    "ID2": [{"TEXT_C": "TIMESTAMP_X"}],
    "ID3": [{"TEXT_E": "TIMESTAMP_Y"}],
}

I know I can easily do this in a for loop but I was wondering if there is a super fancy way.

CodePudding user response:

One way of doing this is using groupby if keys of dictionary are in sorted manner as in your case

from itertools import groupby
in_dict = {
    ("ID1", "TEXT_A"): "TIMESTAMP_X",
    ("ID1", "TEXT_B"): "TIMESTAMP_Y",
    ("ID2", "TEXT_C"): "TIMESTAMP_X",
    ("ID3", "TEXT_E"): "TIMESTAMP_Y",
}
print({k : [{y[1]: in_dict[y]} for y in v]  for k,v in groupby(in_dict, key=lambda x: x[0])})
 # output
 {'ID1': [{'TEXT_A': 'TIMESTAMP_X'}, {'TEXT_B': 'TIMESTAMP_Y'}],
 'ID2': [{'TEXT_C': 'TIMESTAMP_X'}],
 'ID3': [{'TEXT_E': 'TIMESTAMP_Y'}]}

CodePudding user response:

This way,

{ uniq_k : [ {k[1] : v } for k, v in in_dict.items() if uniq_k in k ] for uniq_k in {k[0] for k in in_dict} }
  • Related