16

How does one get a list of attributes/field names of a layer by means of PyQGIS 3?

If my layer has field names seen in the attribute table or properties. How can I use PyQGIS to give me a string list of these field names?

2
  • 6
    The question is pretty clear. Commented Feb 25, 2020 at 0:26
  • 2
    I asked a question in order to create a useful resource for others with the same question. The code attempt (and solution) is in the answer.
    – grego
    Commented Mar 3, 2020 at 22:49

3 Answers 3

28

To get field names with fields() method or other field properties (length, type, comment, ...) you can use:

field_names = [field.name() for field in layer.fields()]
# ['id', 'attr1', 'attr2', 'attr3']

If you just need names, it's sufficient to use:

field_names = layer.fields().names()
# ['id', 'attr1', 'attr2', 'attr3']
15

List field names with dataProvider() method

from qgis.utils import iface

# get active layer if not already set
layer = iface.activeLayer()

prov = layer.dataProvider()

field_names = [field.name() for field in prov.fields()]

for count, f in enumerate(field_names):
    print(f"{count} {f}")

Note: using layer.pendingFields() doesn't seem to work in QGIS 3. See this thread for more details: AttributeError: 'QgsVectorLayer' object has no attribute 'pendingFields'

This fails:

field_names = [field.name() for field in vlayer.pendingFields()]
0
6

Another approach is to use the attributeAliases() method:

Returns a map of field name to attribute alias.

from qgis.utils import iface

layer = iface.activeLayer()
field_names = list(layer.attributeAliases().keys())

Note: the resulting list won't be sorted as fields represented in the attribute table.

It is necessary to apply the .keys(), because the result of attributeAliases() is a dictionary

print (True) if isinstance(layer.attributeAliases(), dict) else False

Your Answer

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

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