0

Given this http response (a Python dictionary)

{"status":1,"list":{"229279689":{"item_id":"229279689",
"resolved_id":"229279689",
"given_url":"http:\/\/www.grantland.com\/blog\/the-triangle\/post\/_\/id\/38347\/ryder-cup-preview",
"given_title":"The Massive Ryder Cup Preview - The Triangle Blog - Grantland",
"favorite":"0",
"status":"0",
"resolved_title":"The Massive Ryder Cup Preview",
"resolved_url":"http:\/\/www.grantland.com\/blog\/the-triangle\/post\/_\/id\/38347\/ryder-cup-preview",
"excerpt":"The list of things I love about the Ryder Cup is so long that it could fill a (tedious) novel, and golf fans can probably guess most of them.",
"is_article":"1",
"has_video":"1",
"has_image":"1",
"word_count":"3197",
"images":{"1":{"item_id":"229279689","image_id":"1",
    "src":"http:\/\/a.espncdn.com\/combiner\/i?img=\/photo\/2012\/0927\/grant_g_ryder_cr_640.jpg&w=640&h=360",
    "width":"0","height":"0","credit":"Jamie Squire\/Getty Images","caption":""}},
"videos":{"1":{"item_id":"229279689","video_id":"1",
    "src":"http:\/\/www.youtube.com\/v\/Er34PbFkVGk?version=3&hl=en_US&rel=0",
    "width":"420","height":"315","type":"1","vid":"Er34PbFkVGk"}}}}}

How can I extract the "given_url" without knowing the "item_id" beforehand? (both are keys located at the top of the response).

ekeen4
  • 352
  • 1
  • 4
  • 10

2 Answers2

0

Try with the following line of code:

try:
    print data['list'].values()[0]['given_url']
except IndexError:
    print "No data"

#output:
http:\\/\\/www.grantland.com\\/blog\\/the-triangle\\/post\\/_\\/id\\/38347\\/ryder-cup-preview
Mani
  • 933
  • 6
  • 15
0

You can use following code to extract all urls in case there many items under list:

urls = [x['given_url'] for x in d['list'].itervalues() if 'given_url' in x]
print urls # ['http:\\/\\/www.grantland.com\\/blog\\/thetriangle\\/post\\/_\\/id\\/38347\\/ryder-cup-preview']
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • Thanks for the input, worked nicely. I'm wondering if you know the name of the formatting where you put x['given_url'] at the beginning and the iterator and conditional at the end of the line of code? – ekeen4 Apr 15 '16 at 18:20
  • What do you mean by the name of the formatting? The `item_id` or something else? – niemmi Apr 16 '16 at 08:32