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
35.8k5 gold badges77 silver badges152 bronze badges
asked Jan 10, 2020 at 19:55
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. 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']
Taras
35.8k5 gold badges77 silver badges152 bronze badges
answered Jan 10, 2020 at 20:37
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
35.8k5 gold badges77 silver badges152 bronze badges
answered Jan 10, 2020 at 19:55
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
answered Dec 5, 2022 at 15:00

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.