2

I am trying to create a schema and domains for existing shp files. Ultimately I want to use this to create a new file 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 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 combination but can't get it. My data is all vector.

Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Jul 23, 2021 at 10:21

1 Answer 1

3

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)
Taras
35.7k5 gold badges77 silver badges151 bronze badges
answered Jul 23, 2021 at 12:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.