Q:

Couldn't replace values in the list using dict conversion in Python

I have below list of dictionaries -
result=[{'cat': '66', 'count': 5, 'ids': [20, 21, 22, 23, 24]},
        {'cat': '27', 'count': 4, 'ids': [20, 22, 23, 24]},
        {'cat': '29', 'count': 2, 'ids': [20, 24]},
        {'cat': '66 & 27', 'count': 4, 'ids': [20, 22, 23, 24]},
        {'cat': '66 & 27 & 29', 'count': 2, 'ids': [20, 24]}
        ]

Am trying to replace cat id with the values based on the dict (conversions), I tried below code
conversions ={'66':'Tesla','27':'Audi','29':'BMW'}
for do in result:
    do['cat']=conversions[do['cat']]

print(result)

This gives me Keyerror for the key '66 & 27', how can I get the result as 'Tesla & Audi'.  For the key '66 & 27 & 29' it should give 'Tesla & Audi & BMW'.
Am not sure how I can handle this scenario. Any suggestions with the approach for achieving this result ?

A:

Split do['cat'] by single space, process each element of the resulting list, and concatenate the result using single space as the separator.
for do in result:
    do['cat'] = ' '.join([conversions.get(x, x) for x in do['cat'].split(' ')])

conversions.get(x, x) returns conversions[x] if x is convertible and x otherwise.
For your data, this approach will produce
[{'cat': 'Tesla', 'count': 5, 'ids': [20, 21, 22, 23, 24]},
 {'cat': 'Audi', 'count': 4, 'ids': [20, 22, 23, 24]},
 {'cat': 'BMW', 'count': 2, 'ids': [20, 24]},
 {'cat': 'Tesla & Audi', 'count': 4, 'ids': [20, 22, 23, 24]},
 {'cat': 'Tesla & Audi & BMW', 'count': 2, 'ids': [20, 24]}]

