1

I am trying to create a schema and domains for existing shp files. Ultimately I want to use this to create a new files with attribute lists.

In QGIS i have a python script that extracts the layers, field name, field type, field length and field precision to a CSV file.

I now want to iterate the each of the layers and generate a list of unique values to see what values have been entered previously. I will skip the fields that shouldn't contain a list, eg ID numbers.

From the "String" fields I wanted to generate a list of unique values, however I am stuck on an if statement that checks in the field is a string type.

listDomains={}
for layer in projectLayers:
    for fields in layer.fields():
        if fields.typeName=='String':
            fieldKey=fields.name()
            fieldValues=list(set(fields.attributes()))
        else:
            continue
        listDomains[fieldKey]=fieldValues
print(listDomains)

When I run above, it bypasses the if statement. I have tried a few combintation but cant get it. My data is all vector.

2

The first problem is you forgot the parentheses after the typeName() method. When you call fields.typeName what is returned is something like:

<built-in method typeName of QgsField object at 0x000002DB4B841C18>

Which will never evaluate as being equal to 'String'.

Secondly, fields.attributes() will cause an attribute error as the QgsField object has no attribute 'attributes()'. Perhaps you are getting confused with the attributes() method of QgsFeature.

The QgsVectorLayer class actually has a method uniqueValues() which takes a field index argument and returns a set containing the unique values in that field so let's use that. Try the code snippet below:

listDomains = {}
for layer in projectLayers:
    for field in layer.fields():
        if field.typeName() == 'String':
            fieldKey = field.name()
            fieldValues = list(layer.uniqueValues(layer.fields().lookupField(field.name())))
        else:
            continue
        listDomains[fieldKey] = fieldValues
print(listDomains)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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