Adding a set of attributes to a vector layer
Each QGIS feature has two parts: the geometry and the attributes. In this recipe, we'll add an attribute for a layer from an existing dataset.
Getting ready...
We will use a point shapefile with museum data for New York City, which you can download as a ZIP file from the following URL:
https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
Extract this shapefile to the following directory: /qgis_data/nyc
How to do it...
While you can add a geometry to a feature without attributes, you must have at least a geometry in order to add attributes. So, we will create a new feature, add some attributes, and then add everything to the layer:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, load the layer and validate it:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
- Next, access the layer's data provider:
vpr = vectorLyr.dataProvider()
- Now, we create a point geometry, which, in this case, is a new museum:
pnt = QgsGeometry.fromPoint(QgsPoint(-74.13401,40.62148))
- Then, we create a new feature and add the geometry:
f = QgsFeature()
- Now, we set the geometry of our new museum feature:
f.setGeometry(pnt)
- Now, we are finally able to add a new attribute. We must set at least one attribute, but we don't have to set all of them. We will just add a name, which is at field position
0
:f.setAttriibuteMap({0:"Python Museum"})
- Finally, we add the feature to the layer and update the extents:
vpr.addFeatures([f]) vectorLyr.updateExtents()
How it works...
Just as geometries are created from Python point lists or tuples, PyQGIS attributes are defined as Python dictionaries specifying the field index position as the key and the attribute as the dictionary value. Python lists and dictionaries are very powerful and flexible data structures. This approach makes adding data to QGIS much easier because you can use the full power of Python data types to build your dataset before defining it with the C-based PyQGIS API.