简体   繁体   中英

How to check if key exist in data, if exist then do for loop else ignore using list comprehension in python

I have data(dictionary format) that contains keys and values, I want to display that data using list comprehensions.

data = { 'memberships': 'type of membership' }

Note: The data is different for each profile(for eg: membership is available for only few users.)

Attempt1:

memberships = [data['memberships'][mem] for mem in data['memberships']]
print(memberships)

The above code is working for the users having a membership. If membership does not exist it will thrown an KeyError.

Attempt2:

memberships =[data['memberships'][mem] for mem in data['memberships'] if 'memberships' in data]

Attemp3:

memberships=[data['memberships'][mem] if "memberships" in data else '' for mem in data['memberships']]

I tried but failed with KeyError for all the attempts. I want to check the membership(key) if exists I will loop and display it else ignoring

You can always use an if statement:

if 'membership' in data.keys():
    memberships = [data['memberships'][mem] for mem in data['memberships']]
    print(memberships)
else:
    #Do something else if you wish
    pass

Another option (if it suits your code better) is to use try and except, although I doubt you need this approach:

try:
    #Will try to execute this code
    memberships = [data['memberships'][mem] for mem in data['memberships']]
    print(memberships)

except:
    #If a KeyError occurs, the try block will stop and this part of the code will execute
    pass

Hope this helps! If you have any questions with my answer feel free to ask.

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