繁体   English   中英

使用括在列表中的嵌套字典更改python中多维数字dict的值

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

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

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

我想加密dict中的值。 我坚持解析列表中的内部dicts

我的代码是这样的:

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?'}]}

它使用递归函数迭代嵌套的dict,包括任意数量级别的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM