Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

i look for solution to get the unique values of an attribute of a vector layer. what is the best way in python qgis to get the unique values of one distinct attribute? I work with qgis 1.8.0.

share|improve this question
    
In QGIS without python you could just query the FieldCalculator with all unique values of a field (there is a button on the right side). A pythonic solution would also be possible. What do you need this value for? Please elaborate a bit –  Curlew Oct 8 '13 at 17:42
    
i have polygons described by an attribute "group". Each group contains 1 to about 10 polygons. I want to process the polygons belonging to a certain group in for-loop, i.e. for each iteration of the for-loop i select the polygons with setSubsetString to process this group, e.g. to write them to a shape file. However i do not know the group befor reading the vector layer. –  gallay Oct 8 '13 at 18:30
1  
There is a split tool which will create separate shapefiles depending on an attribute if that's all you need. Otherwise, that plugin would also be the place to look for sample code. –  underdark Oct 8 '13 at 18:58
    
From the plugin you were mentioned the function split in splitterdialog.py is what i was looking for. Thank you for the hint! –  gallay Oct 8 '13 at 20:04

1 Answer 1

Python's sets are handy for finding unique values. For example:

>>> set(range(4) + range(5) + range(6))
set([0, 1, 2, 3, 4, 5])

Try something like this (pyqgis 1.8):

values = set()
layer.select()
for feature in layer:
    index = layer.fieldNameIndex(ATTRNAME)
    values.add(feature.attributeMap()[index].toInt())

Pyqgis 2.0:

values = set()
for feature in layer.getFeatures():
    values.add(feature[ATTRNAME])
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.