Reputation: 49
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
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