2

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) }
5
  • what is the expected output ? Commented Oct 27, 2017 at 8:34
  • @SachinKukreja The same structure but with all dict values encrypted I guess. Commented Oct 27, 2017 at 8:35
  • 2
    Will you be able to read and understand your code in two days? Huge one-liners are satisfying in the very-short run, but they are bad code (in terms of maintainability). Commented Oct 27, 2017 at 8:40
  • 1
    Yes my frist reaction was that although it may seem "pythonic" to make that encryption a 1-liner, its not easy to understand, which makes it then not "pythonic". Commented Oct 27, 2017 at 8:41
  • 1
    Exactly, "one-liner" is not a pythonic property. Its just that often one-liners are very clear in python, and that makes them "pythonic". Commented Oct 27, 2017 at 8:49

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That fix my problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.