2

I'm trying to write python script in QGIS to merge layers having the same name.

To do that I specify the name of layer in the script, so all layers having this name, will be merged. However, since I have a lot of names this is not practical. I tried to convert the names type from unicode to list to be able to iterate in the list of names.

In this script, I specify layer name. I want to iterate over all names and compare them to finally merge layers having same name.

import qgis.core
import processing
def __init__(self, iface):
    self.iface = iface
lyr_list=[]
count=1
layers=iface.mapCanvas().layers()
for i in layers:
    if i.name() == 'layer_name':
        lyr_list.append(i)

processing.runandload("qgis:mergevectorlayers", lyr_list, "memory:merged")
4
  • please share your script, so we can answer your question more precisely!
    – Riccardo
    Commented Sep 13, 2019 at 11:28
  • Have you tried to create a dictionary where the key is the layername, and the value is a list of all the layers that have that name? Once you have a dictionary populated you should be able to runandload once for each key in the dictionary. Commented Sep 13, 2019 at 20:37
  • Thanks@Kirk Kuykendall for your response. How can I create this dictionary in python?
    – nermiiine
    Commented Sep 14, 2019 at 15:49
  • @nermiiine In my answer you have an example of this parameters dictionary.
    – xunilk
    Commented Sep 19, 2019 at 20:00

1 Answer 1

1

Following code has an example of parameters dictionary and, I modified some little thing in your code because you are tagged this question with qgis-3 and 'runandload' doesn't exist as processing method in pyqgis3. I also modified 'layer_name' for working with my own layers.

import qgis.core
import processing
def __init__(self, iface):
    self.iface = iface
lyr_list=[]
count=1
layers=iface.mapCanvas().layers()
for i in layers:
    if i.name() == 'polygon1':
        lyr_list.append(i)

processing.runAndLoadResults("qgis:mergevectorlayers", 
                             {'LAYERS': lyr_list, 
                              'OUTPUT': "memory:merged"})

So, I loaded same layer twice in Map Canvas of QGIS 3 and, I ran above script in Python Console.

Result (layer Merged) can be observed in following image with attributes table. It worked.

enter image description here

1
  • Thank you @xunilk for your answer, just I don't want to specify the layer name in the code. So I tried to create a combobox which display layers name. It work fine. If you have any other suggestions will be very helpful
    – nermiiine
    Commented Sep 20, 2019 at 18:03

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.