0

i have dictionary

myd = {
  'Items': [{'key':2}
    
  ],
  'Count': 1, 
  'RetryAttempts': 0
  }

I m printing the key with below

print(myd['Items'][0].get('key'))

I have dictionary which 'Items' is empty

myd = {
  'Items': [
    
  ],
  'Count': 0, 
  'RetryAttempts': 0
  }

If I try with print(a['Items'][0].get('key')) I m getting index out of range error

Is there any i can do in list comprehension, if key is not present then need to get empty string or None

sim
  • 524
  • 3
  • 14
  • 2
    `print(a['Items'][0].get('key') if a['Items'] else None)` – Selcuk Apr 19 '21 at 05:48
  • 1
    If the `Items` key can be unset when it is empty, then for the same effect you could also do: `if a.get('Items') else None` – flakes Apr 19 '21 at 06:14

0 Answers0