例如,假设我有一个这样的字典:
bulk_details={
"ad":'ad',
'ad':[
{'ad':'ad'},
{'ad':'ad'}
]
}
我想加密字典中的值。我一直在解析列表中的内部字典
我的代码是这样的:
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) }
最佳答案
这并不像你的一行那么紧凑,但它解决了你的问题,你也许可以使它更紧凑:
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?'}]}
它使用递归函数迭代嵌套字典,包括任意数量级别的数组。
关于python - 更改Python中多维字典的值,其中嵌套字典包含在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970750/