python - 更改Python中多维字典的值,其中嵌套字典包含在列表中

标签 python dictionary

例如,假设我有一个这样的字典:

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/

相关文章:

访问目录列表中每个文件的pythonic方式

python - 能源消耗最大化

python - 从作为列表的字典值中选择时,random.choice 不起作用

c# - 为什么我的 Dictionary 类看不到 ToArray() 方法?

python - 多键字典初始化的代码更少

python - 如何捕获导致 argparse 在 Python 中引发错误的值

python - 我如何编写一个程序来单击Python中的特定链接

Python:循环字典,一次两个键

Python 用字典格式填充字符串

python - 如何在不指定库存但直接指定主机的情况下运行 Ansible?