2

I have a list of attributes in QGIS:

[137.0, u'0101S', u'MUNICIPIO', u'28004', 19849.4753178, 22000935.5836, u'\Alamo, El']

And I am trying to obtain each element in the list, using pyqgis.

I can't use a simple loop , like

for feature in features:
    print feature

because it returns the object id.

And if I use this:

for feature in features:
print '\n'.join(feature)

It returns the following error:

TypeError: sequence item 0: expected string, float found

*For example, my aim is:

"value1" = 137.0

"value2" = 0101S

and so on.

2
  • 1
    Not sure what you mean by split (assign each value in the list to a incremented variable?), can you expand more what you mean by this?
    – artwork21
    Apr 14, 2016 at 12:07
  • I have put : "obtain". I mean, get every value of the list, print it separately, in different lines.
    – user64823
    Apr 14, 2016 at 12:32

2 Answers 2

2

Perhaps something like the following?

layer = qgis.utils.iface.activeLayer()
for feature in layer.getFeatures():
    attrs = feature.attributes()
    for i, j in list(enumerate(attrs)):
        print "value" + str(i + 1) + " = " + str(j)
2
  • Thank you very much, I was looking for the split method... I couldn't manage it. This makes all sense to me
    – user64823
    Apr 14, 2016 at 13:16
  • Most welcome but I would suggest noting @artwork21's answer as the methods described are in my opinion easier to handle ;)
    – Joseph
    Apr 14, 2016 at 13:19
2

To print the field value you need to provide the field name or index:

Field Name:

for feature in LYR.getFeatures():
    print feature['myFieldName']

Field Index (first field starts at zero):

for feature in LYR.getFeatures():
    print feature[1] # this is the second field in the table
1
  • Thank you very much!. This is a easier method to take into account.Both answers are right.. I can't check both.
    – user64823
    Apr 14, 2016 at 13:18

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.