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.
1 Answer 1
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)
Explore related questions
See similar questions with these tags.