How is it possible to create a list from the values of a single field in a shp using PyQGIS?
Example:
| field_capital_name |
|---|
| London |
| Paris |
| Rome |
list1 = [London, Paris, Rome]
How is it possible to create a list from the values of a single field in a shp using PyQGIS?
Example:
| field_capital_name |
|---|
| London |
| Paris |
| Rome |
list1 = [London, Paris, Rome]
A solution based on the usage of QgsAggregateCalculator with ArrayAggregate and StringConcatenateUnique parameters.
Available aggregates to calculate.
Not all aggregates are available for all field types.
This approach is available since QGIS 2.16.
Let's assume there is a layer called 'test' with several features in it, see the image below. In my example, I will refer to the field "test".
With the following script it is possible to create a list from the values of a single field:
layer = iface.activeLayer()
list_of_values = layer.aggregate(QgsAggregateCalculator.ArrayAggregate, "test")[0]
print(list_of_values)
which will result in this:
['Lorem ipsum 1', 'Lorem ipsum 2', 'Lorem ipsum 1']
To get only unique values, apply the following:
layer = iface.activeLayer()
params = QgsAggregateCalculator.AggregateParameters()
params.delimiter = ","
list_of_values = layer.aggregate(QgsAggregateCalculator.StringConcatenateUnique, "test", params)[0].split(",")
print(list_of_values)
which will result in this:
['Lorem ipsum 1', 'Lorem ipsum 2']
Keep in mind that list sorting is not covered in this answer.
References:
Use getFeatures:
lyr = QgsProject.instance().mapLayersByName('ok_an_riks')[0]
list1 = [f['lansnamn'] for f in lyr.getFeatures()]
# reference to the layer
lyr = iface.activeLayer()
# get its fields
fields = lyr.fields()
# get the index of the field
idx = fields.indexFromName('my_field_name')
# get unique values
uniq_vals = lyr.uniqueValues(idx)
# get all values
all_vals = []
for f in lyr.getFeatures():
all_vals.append(f[idx])
# or skip getting the index
# all_vals.append(f['my_field_name'])
A solution using QgsVectorLayerUtils
Contains utility methods for working with
QgsVectorLayers.
This approach is available since QGIS 3.
Let's assume there is a layer called 'test' with several features in it, see image below. In my example, I will refer to the field "test".
With the following script it is possible to create a list from the values of a single field:
layer = iface.activeLayer()
list_of_values = QgsVectorLayerUtils.getValues(layer, 'test')[0]
print(list_of_values)
which will result in this:
['Lorem ipsum 1', 'Lorem ipsum 2', 'Lorem ipsum 1']
To get only unique values, apply the following:
layer = iface.activeLayer()
list_of_values = QgsVectorLayerUtils.getValues(layer, 'test')[0]
list_of_values = list(set(list_of_values))
print(list_of_values)
which will result in this:
['Lorem ipsum 1', 'Lorem ipsum 2']
Keep in mind that list sorting is not covered in this answer.