简体   繁体   中英

How can I beautifully deal with this dirty-multiple-try code

Hi guys please help me to revise this code. You probably know what I'm trying to do It isn't critical to have keyError but anyway I want to try every del code. It works as I intended, but I'm pretty sure there is more beautiful way to do this.

try:
    del response_json['sha1']
except:
    print("keyError: Fail to delete sha1 hash key")
try:
    del response_json['sha224']
except:
    print("keyError: Fail to delete sha224 hash key")
try:
    del response_json['sha256']
except:
    print("keyError: Fail to delete sha256 hash key")
try:
    del response_json['sha384']
except:
    print("keyError: Fail to delete sha384 hash key")
try:
    del response_json['sha512']
except:
    print("keyError: Fail to delete sha512 hash key")   

I can do this as below but this way if first del code raise error, then the rest of code will not be executed, right?

try:
    del response_json['sha1']
    del response_json['sha224']
    del response_json['sha256']
    del response_json['sha384']
    del response_json['sha512']
except:
    print("keyError: Fail to delete hash key")

Thank you for reading this

Use a loop to iterate the values

lst = ['sha1','sha224','sha256','sha384','sha512']
for s in lst:
    try:
        del response_json[s]
    except:
        print(f"keyError: Fail to delete {s} hash key")

I think response_json is a dictionary and not just a list. I think you need something that is more dynamic and adaptable to all situations. Just populate the keys and delete each key-value pair one after the other. This solution goes for any length and any dictionary you might encounter in the future.

json_keys = [ key for key in response_json]
for keys in json_keys:
    try:
        del response_json[keys]
    except:
        print(f"keyError: Fail to delete hash key")      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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