Obtaining the data of one selected feature in QGIS using Python?
Calling layer.selectedFeatures()
will return a list with your selected feature(s). You can then call feature.attributeMap()
on each of the selected features to get a dictionary of each feature's attributes.
layer = qgis.utils.iface.activeLayer()
selected_features = layer.selectedFeatures()
for i in selected_features:
attrs = i.attributeMap()
for (k,attr) in attrs.iteritems():
print "%d: %s" % (k, attr.toString())
I recently had a similar question answered here: When iterating over a vector layer with pyqgis, how do I check whether a feature is selected?
I just wanted to post some updates to the previous answer in light of changes to the QGIS Python API since version 2.0.
As before, you would get a list of selected features with iface.activeLayer().selectedFeatures()
, however in QGIS
versions >= 2.0
you now use the function QgsFeature.attributes()
instead of QgsFeature.attributeMap()
. The two functions are not exactly the same: attributes()
now returns a list, whereas the old attributeMap()
returned a dictionary. Take a moment to browse the API documentation for QgsFeature.attributes()
, QgsAttributes
, etc to understand how attributes are stored/accessed.
If you're interested, you can read about some of the rationale behind the API changes on this mailing list thread: [Qgis-developer] new vector api select features. Briefly (in the words of QGIS developer Martin Dobias):
Access to attributes: there is no
f.attributeMap()
anymore, because attributes are now stored in a vector (Python:list
) instead of a map (Python:dict
).QgsFeature
class emulates python container object 4 so you can access attributes as ifQgsFeature
instance was a list or dictionary, with keys being either field indices or field names:
f[0]
... first attribute
f["type"]
... attribute named "type"It is still possible to get all attributes:
f.attributes()
returns a list of values.
So as an example of specifically what you asked how to do (get data for a single feature you've selected), suppose you had a layer of containing city
features that each have a list of attributes, including a county
attribute. To get the county
value for a specific city you've selected (say Helena, AR
), do the following in the Python console:
city = iface.activeLayer().selectedFeatures()[0]
city["county"]
# OUTPUTS: u'Phillips'
If you want the values of all of the fields in the city's attribute table, then you would just use:
cityData = city.attributes()