Skip to content

Latest commit

 

History

History
75 lines (54 loc) · 2.28 KB

Extract a record by name in pyshp?.md

File metadata and controls

75 lines (54 loc) · 2.28 KB

from Extract a record by name in pyshp?

You can easily create a dictionary of attributes:

    import shapefile
    sf = shapefile.Reader('MyFile.shp')
    # name of fields
    fields = sf.fields[1:] 
    field_names = [field[0] for field in fields] 
    # construction of a dctionary field_name:value  
    for r in sf.shapeRecords():  
         atr = dict(zip(field_names, sr.record))  

As a result:

    {'field1': 'value1', 'field2': 'value2', ...,  'fieldn': 'valuen'}

and

    if atr['field1'] == value:
           print atr
           action

With large/many files, you can use a generator:

    def records(filename):  
        # generator 
        reader = shapefile.Reader(filename)  
        fields = reader.fields[1:]  
        field_names = [field[0] for field in fields]  
        for sr in reader.shapeRecords():   
            yield dict(zip(field_names, sr.record)) 
    rec = records('MyFile.shp')
    rec.next()
    {'field1': 'value1', 'field2': 'value2', ...,  'fieldn': 'valuen'}
    # or
    for rec in records('MyFile.shp')
         if rec['field1'] == value:
             data = rec

Sean Gillies has proposed the The geo_interface protocol, an interface that describes a spatial object using a GeoJSON like structure (dictionaries). Many modules implement this protocol (see Python Geo_interface applications), including pyshp, since version 1.1.7:

With one of my examples:

    for r in sf.shapeRecords():  
       atr = dict(zip(field_names, r.record))  
       geom = r.shape.__geo_interface__ 
       print dict(geometry=geom,properties=atr)  
       {'geometry': {'type': 'Point', 'coordinates': (161821.09375, 79076.0703125)}, 'properties': {'DIP_DIR': 120, 'STRATI_TYP': 1, 'DIP': 30}}

You can also use Fiona or osgeo.ogr in the same way.