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?

Taras
  • 32,823
  • 4
  • 66
  • 137
grego
  • 1,043
  • 7
  • 18

3 Answers3

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']
Taras
  • 32,823
  • 4
  • 66
  • 137
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
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()]
Taras
  • 32,823
  • 4
  • 66
  • 137
grego
  • 1,043
  • 7
  • 18
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
Taras
  • 32,823
  • 4
  • 66
  • 137