The QgsJsonUtils
class has exportAttributes
method for getting attributes as a dict
.
Solution 1:
Making a dictionary including feature "id"
as key, attributes map as value:
{feature1.id: {attr1: value, attr2: value, ...},
feature2.id: {attr1: value, attr2: value, ...},
...}
from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName('LAYER_NAME')[0]
features_dict = {f.id(): QgsJsonUtils.exportAttributes(f) for f in layer.getFeatures()}
Solution 2:
Making a list including attributes map (dict
) of features:
[{attr1: value, attr2: value, ...}, # feature 1
{attr1: value, attr2: value, ...}, # feature 2
...]
from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName('LAYER_NAME')[0]
features_list = [QgsJsonUtils.exportAttributes(f) for f in layer.getFeatures()]