Search code examples
pythondictionarykeylist-comprehensiondefaultdict

How to convert/update the key-values information in defaultdict?


How do I convert the following defaultdict()?

defaultdict(<class 'dict'>, {
  'key1_A': {
    'id': 'key1',
    'length': '663', 
    'type': 'A'},
  'key1_B': {
    'id': 'key1',
    'length': '389',
    'type': 'B'},
  'key2_A': {
    'id': 'key2',
    'length': '865',
    'type': 'A'},
  'key2_B': {
    'id': 'key2',
    'length': '553',
    'type': 'B' ........}})
  • the value of the id i.e key1 becomes the key, and the key called length is changed to length_A or B with corresponding values belonging in the earlier type.

    defaultdict(<class 'dict'>, { 'key1': { 'length_A': '663', 'length_B': '389'}, 'key2': { 'length_A': '865', 'length_B': '553'}})

Thanks,


Solution

  • I think this does what you want:

    from collections import defaultdict
    import pprint
    
    d = {
        'key1_A': {
            'id': 'key1',
            'length': '663', 
            'type': 'A',
        },
        'key1_B': {
            'id': 'key1',
            'length': '389',
            'type': 'B',
        },
        'key2_A': {
            'id': 'key2',
            'length': '865',
            'type': 'A',
        },
        'key2_B': {
            'id': 'key2',
            'length': '553',
            'type': 'B',
        },
    }
    
    transformed = defaultdict(dict)
    for v in d.values():
        transformed[v["id"]]["length_{}".format(v["type"])] = v["length"]
    
    pprint.pprint(transformed)
    
    # Output:
    # defaultdict(<class 'dict'>,
    #             {'key1': {'length_A': '663', 'length_B': '389'},
    #              'key2': {'length_A': '865', 'length_B': '553'}})