Home > Net >  Combining dictionary that contains lists, on another dictionary
Combining dictionary that contains lists, on another dictionary

Time:12-14

I have the follow dictionary: dict1

{
    '1': {
        'departure_date': datetime.date(2023, 6, 6),
        'airline': 'QR'
    },
    '2': {
        'departure_date': datetime.date(2023, 6, 7),
        'airline': 'QR'
    },
    '3': {
        'departure_date': datetime.date(2023, 6, 23),
        'airline': 'QR'
    },
    '4': {
        'departure_date': datetime.date(2023, 6, 24),
        'airline': 'QR'
    }
}

And the following dictionary: dict2

{
    1: [1, 2],
    2: [1, 2]
}

Desired output should be the following:

{
    '1': {
        '1': {
            'departure_date': datetime.date(2023, 6, 6),
            'airline': 'QR'
        },
        '2': {
            'departure_date': datetime.date(2023, 6, 7),
            'airline': 'QR'
        }
    },
    '2': {
        '1': {
            'departure_date': datetime.date(2023, 6, 23),
            'airline': 'QR'
        },
        '2': {
            'departure_date': datetime.date(2023, 6, 24),
            'airline': 'QR'
        }
    }
}

The combined list should look as the above.

It should take the dict2 as the structure if I can call it that.

CodePudding user response:

One approach:

itd1 = iter(dict1.values())
res = {k: {v: next(itd1) for v in vs} for k, vs in dict2.items()}
print(res)

Output

{1: {1: {'airline': 'QR',
         'departure_date': datetime.datetime(2023, 6, 6, 0, 0)},
     2: {'airline': 'QR',
         'departure_date': datetime.datetime(2023, 6, 7, 0, 0)}},
 2: {1: {'airline': 'QR',
         'departure_date': datetime.datetime(2023, 6, 23, 0, 0)},
     2: {'airline': 'QR',
         'departure_date': datetime.datetime(2023, 6, 24, 0, 0)}}}

The above dictionary comprehension is equivalent to the following nested for loops:

itd1 = iter(dict1.values())
res = {}
for k, vs in dict2.items():
    row = {}
    for v in vs:
        row[v] = next(itd1)
    res[k] = row

CodePudding user response:

from collections import defaultdict
d3 = defaultdict(dict)
   for k2, values2 in d2.items():
      for value2 in values2:
         d3[str(k2)][str(value2)] = d1[str(k2)]
  • Related