I want to get a list of field names of a layer using QGIS expressions. The function attributes() returns a key:value map of the attribute names and values. By default, the result is sorted alphabetically based on the attribute name. To get an alphabetical list of attribute names alone, I can use map_akeys(attributes()). This works fine. For those interested: the question arose with this use case.


How can the sort order be changed so that the order is not alphabetical, but reproduces the order in the attribute table?

Alphabetical sort order does not correspond to the order in the attribute table:

enter image description here

What I tried

A workaround for a custom order is ordering it manually with the new array_prioritize function (available since QGIS 3.20). However, the sort order has to be defined manually and thus eliminates the advantage of automatically getting a list of all attributes with map_akeys(attributes()):

    array ('grassland','forest','steppe','other','value5','value6','value7','value8','value9','value10','value11', 'value12')

enter image description here

1 Answer 1


A simple custom function will do that :

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='GIS SE', referenced_columns=[])
def ordered_fields(feature, parent):
    return feature.fields().names()

To use : ordered_fields()

  • 1
    I like this part group='GIS SE' :)
    – Taras
    Nov 2, 2021 at 7:10

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.