3

I'm writing a QGIS processing plugin. In this plugin, I use the processing algorithm pointsalonglines, and for the distance parameter, I'd like to use an expression which gives back the value of a dictionary with the key equal to a field value. Not sure that is clear but basically:

mydic = {"id1" : 1, "id2" : 2}

and the parameters for pointsalonglines algorithm, something like this :

param2 = {'INPUT':layer,
          'DISTANCE': QgsProperty.fromExpression(mydic["idfield"]),
          'START_OFFSET':0,
          'END_OFFSET':0,
          'OUTPUT':'test'}

where idfield is the name of an existing field in my layer, with values = "id1", "id2", ...

I tried many ways to write my expression but without any success.

4
  • 1
    Welcome to GIS SE ! Have you tried something like : QgsProperty.fromExpression("map_get(map('id1', 1, 'id2', 2), \"idfield\")") ? Jan 4, 2021 at 16:29
  • Thanks a lot, it works ! I first created the list of keys and values from my dictionary : mymap = [] for k, v in mydic.items(): mymap.extend([k, v]) mymap = tuple(mymap) then I used : QgsProperty.fromExpression("map_get(map{}, {})".format(str(mymap), \"idfield\"))
    – Julie
    Jan 4, 2021 at 20:48
  • By the way, thanks a lot for the amazing QGIS tutorial. Jan 5, 2021 at 8:47
  • That's great if it's useful, thanks a lot !
    – Julie
    Jan 6, 2021 at 8:49

1 Answer 1

1

You need for that to place as string in QgsProperty.fromExpression(...) a QGIS expression, so, you can have the same behavior with a map (not a GIS one this time) :

from functools import reduce

mydict = {"id1" : 1, "id2" : 2}
qgis_expr = f'map_get(map{reduce(lambda x, y: x + y, mydict.items())}, "idfield")'
param2 = {
  'INPUT':layer,
  'DISTANCE': QgsProperty.fromExpression(qgis_expr),
  'START_OFFSET':0,
  'END_OFFSET':0,
  'OUTPUT':'test'
}
1
  • Great, thanks !! It works ! I had to remove the quotes around the field name though : qgis_expr = f'map_get(map{reduce(lambda x, y: x + y, mydict.items())}, idfield)' or if my field name is a variable : fieldname = "idfield" qgis_expr = f'map_get(map{reduce(lambda x, y: x + y, mydict.items())}, {fieldname})'
    – Julie
    Jan 6, 2021 at 8:37

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.