dastiv21
dastiv21

Reputation: 49

change the value of a multidimentional dict in python with nested dict enclosed in a list

for example, let's say i have a dict like this:

bulk_details={
    "ad":'ad',
    'ad':[
        {'ad':'ad'},
        {'ad':'ad'}
    ]
}

I want to encrypt the values in the dict. i'm stuck at parsing the inner dicts inside the list

my code is this:

new_data = {key: {key_: encrypt(val_) for key_, val_ in (val.items() if type(val) is dict else val)} for key, val in (bulk_details.items() if type(bulk_details) is dict else bulk_details) }

Upvotes: 2

Views: 58

Answers (1)

Lukas Ansteeg
Lukas Ansteeg

Reputation: 341

This is not nearly as compact as your one-liner, but it solves your problem and you can perhaps make it more compact:

bulk_details = {
    'ad':'ad',
    'ad2':
        [
            {'ad':'ad'},
            {'ad':'ad'}
        ]
}

def encrypt(to_encrypt):
    return '?' + to_encrypt + '?'

def encrypt_nested(dt):
    if isinstance(dt, dict):
        for key, value in dt.items():
            if isinstance(value, str):
                dt[key] = encrypt(value)
            else:
                encrypt_nested(value)
        return dt
    else: # elif isinstance(dt, list)
        for value in dt:
            if isinstance(value, str):
                value = encrypt(value)
            else:
                encrypt_nested(value)
        return dt

print(encrypt_nested(bulk_details))
# {'ad': '?ad?', 'ad2': [{'ad': '?ad?'}, {'ad': '?ad?'}]}

It iterates through a nested dict including arrays for any amount of levels using a recursing function.

Upvotes: 4

Related Questions