Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find value matching value in a list of dicts

Tags:

python

I have a list of dicts that looks like this:

serv=[{'scheme': 'urn:x-esri:specification:ServiceType:DAP',
  'url': 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/air.mon.anom.nobs.nc'},
 {'scheme': 'urn:x-esri:specification:ServiceType:WMS',
  'url': 'http://www.esrl.noaa.gov/psd/thredds/wms/Datasets/air.mon.anom.nobs.nc?service=WMS&version=1.3.0&request=GetCapabilities'},
 {'scheme': 'urn:x-esri:specification:ServiceType:WCS',
  'url': 'http://ferret.pmel.noaa.gov/geoide/wcs/Datasets/air.mon.anom.nobs.nc?service=WCS&version=1.0.0&request=GetCapabilities'}]

and I want to find the URL corresponding to the ServiceType:WMS which means finding the value of url key in the dictionary from this list where the scheme key has value urn:x-esri:specification:ServiceType:WMS.

So I've got this that works:

for d in serv:
    if d['scheme']=='urn:x-esri:specification:ServiceType:WMS':
        url=d['url']
print url

which produces

http://www.esrl.noaa.gov/psd/thredds/wms/Datasets/air.mon.anom.nobs.nc?service=WMS&version=1.3.0&request=GetCapabilities

but I've just watched Raymond Hettinger's PyCon talk and at the end he says that that if you can say it as a sentence, it should be expressed in one line of Python.

So is there a more beautiful, idiomatic way of achieving the same result, perhaps with one line of Python?

Thanks, Rich

like image 765
Rich Signell Avatar asked Feb 17 '23 22:02

Rich Signell


1 Answers

The serv array you listed looks like a dictionary mapping schemes to URLs, but it's not represented as such. You can easily convert it to a dict using list comprehensions, though, and then use normal dictionary lookups:

url = dict([(d['scheme'],d['url']) for d in serv])['urn:x-esri:specification:ServiceType:WMS']

You can, of course, save the dictionary version for future use (at the cost of using two lines):

servdict = dict([(d['scheme'],d['url']) for d in serv])
url = servdict['urn:x-esri:specification:ServiceType:WMS']
like image 175
Nikita Borisov Avatar answered Apr 27 '23 00:04

Nikita Borisov