Grouping based on the dictionary keys

Viewed 59

I have a Dictionary as below:

    dict_details = {
        'device.dummy.1.id': '1',
        'device.dummy.2.id': '2',
        'device.dummy.1.length': '202',
        'device.dummy.2.length': '203',
        'device.dummy.2.validity': '10001',
        'device.dummy.1.validity': '10002',
        'device.dummy.1.type': 'first',
        'device.dummy.2.type': 'first'
    }

I need to create a following dictionary with the above dictionary. That is group the dictionary values with some unique identifier which will be present in my dict.

{
    'device.dummy.1': {
        'id': '1',
        'length': '202',
        'validity': '10001',
        'type': 'first'
    },
    'device.dummy.2': {
        'id': '2',
        'length': '203',
        'validity': '10002',
        'type': 'first'
    }
}

I tried the following code:

    dict_details = {
        'device.dummy.1.id': '1',
        'device.dummy.2.id': '2',
        'device.dummy.1.length': '202',
        'device.dummy.2.length': '203',
        'device.dummy.2.validity': '10001',
        'device.dummy.1.validity': '10002',
        'device.dummy.1.type': 'first',
        'device.dummy.2.type': 'first'
    }
    s = {}
    dummy = {}
    for key, value in dict_details.items():

        attrib = key.rsplit(".",1)[1]
        macro = key.rsplit(".",1)[0]
        s[attrib] = value
        dummy[macro] = s
    print(dummy)

But It is generating a output as below, That is key's value getting overwritten by the already existing keys.

Looking for the some simple workaround for the same.

{
    'device.dummy.1': {
        'length': '202',
        'type': 'first',
        'id': '1',
        'validity': '10001'
    },
    'device.dummy.2': {
        'length': '202',
        'type': 'first',
        'id': '1',
        'validity': '10001'
    }
}
3 Answers
Related