title: Tweepy python code returns KeyError on 'media' entity when tweet does not contain image
body: <p>Hi people of StackOverflow</p>
  
  <p>I am relatively new to Tweepy/Twitter API and am having a few issues getting it to return the URL's for images.</p>
  
  <p>Basically, I have written a snippet of code that searches for tweets against a particular hashtag, then returns image URL entities that exist in the tweets. I am hitting an issue however when a tweet is returned that does not have any media in it. Error shown below:</p>
  
  <pre><code>Traceback (most recent call last):
  File "./tweepyTest.py", line 18, in &lt;module&gt;
  for image in  tweet.entities['media']:
  KeyError: 'media'
  </code></pre>
  
  <p>Below is my code:</p>
  
  <pre><code>for tweet in tweepy.Cursor(api.search,q="#hashtag",count=5,include_entities=True).items(5):
          #print tweet.text
          for image in  tweet.entities['media']:
              print image['media_url']
  </code></pre>
  
  <p>I am guessing I need to encase the for loop in some kind of if statement, however I am struggling to get my head around how.</p>
  
  <p>Any help would be much appreciated.</p>
  
  <p>EDIT:
  I think I might have found a solution, however i'm not sure it is particularly elegant.....using a try/except.</p>
  
  <pre><code>for tweet in tweepy.Cursor(api.search,q="#hashtag",count=5,include_entities=True).items(5):
      #print tweet.text
      try:
              for image in  tweet.entities['media']:
                      print image['media_url']
      except KeyError:
              pass
  </code></pre>