title: How to check if key exist in data, if exist then do for loop else ignore using list comprehension in python
body: <p>I have data(dictionary format) that contains keys and values, I want to display that data using list comprehensions.</p>
  <p>data = {
  'memberships': 'type of membership'
  }</p>
  <p><strong>Note:</strong> The data is different for each profile(for eg: <strong>membership</strong> is available for only few users.)</p>
  <p><strong>Attempt1:</strong></p>
  <pre><code>memberships = [data['memberships'][mem] for mem in data['memberships']]
  print(memberships)
  </code></pre>
  <p>The above code is working for the users having a membership. If membership does not exist it will thrown an KeyError.</p>
  <p><strong>Attempt2:</strong></p>
  <pre><code>memberships =[data['memberships'][mem] for mem in data['memberships'] if 'memberships' in data]
  </code></pre>
  <p><strong>Attemp3:</strong></p>
  <pre><code>memberships=[data['memberships'][mem] if &quot;memberships&quot; in data else '' for mem in data['memberships']]
  </code></pre>
  <p>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</p>