Group layer script is also duplicating layers?

505
2
01-27-2023 05:22 AM
Davec43
Occasional Contributor

I have a script that a co-worker made that I'm trying to utilize. What I have is two types of layers (points/lines) with the same name's points (A, B, C) and lines (A, B, C). The Script will group the layers into groups with the same name. The problem is it will also duplicate the layers, so I'll have a list of grouped layers and non-grouped layers. How do I keep the script from duplicating the layers?

 

 

 

import arcpy

import random
from itertools import groupby
from collections import defaultdict

aprx = arcpy.mp.ArcGISProject("CURRENT")
act_map = aprx.activeMap
map1 = aprx.listMaps("Map1")

layer = act_map.listLayers()
lyr_list = []
for position in range(0, len(layer)):
    lyr_name = layer[position].name
    lyr_list.append(lyr_name)
all_indexes = []
for i in range(0, len(layer)):
    all_indexes.append(layer[i])
    lyr_list2 = all_indexes
merge_lyr_list = defaultdict(list)
for key, value in zip(lyr_list, lyr_list2):
    merge_lyr_list[key].append(value)
overall_lyr_list = merge_lyr_list
mykeys = list(overall_lyr_list.keys())
mykeys.sort()
sorted_lyr_list = {i: overall_lyr_list[i] for i in mykeys}
layer = act_map.listLayers()
grplayer = act_map.listLayers("New Group Layer")[0]
for group_name, layers in sorted_lyr_list.items():
    group = act_map.addLayer(grplayer)[0]
    group.name = group_name
    for lyr in layers:
        act_map.addLayerToGroup(group, lyr)

 

 

0 Kudos
2 Replies
DanPatterson
MVP Esteemed Contributor

There is a suggestion in...

Map—ArcGIS Pro | Documentation

regarding what you might have to do with layers having the same name

It is possible that there might be layers in a map that have the same name. If that is the case, then other properties may need to be used to isolate a specific layer. Properties such as a layer's datasource or definitionQuery could be used to do this. It is ideal that all layers in a map be uniquely named.


... sort of retired...
DanielMiranda2
Occasional Contributor

Assuming I have understood the script correctly (I am still somewhat new with Python), I think adding one line of code at the end will get rid of the ungrouped layers:

 

act_map.removeLayer(lyr)

 

This would have to be indented under.

 

for lyr in layers:

What is actually happening is addLayerToGroup does not "move" the layer, but rather adds it to the map as a layer within the group. If you specified a layer file for example, the layer file would still exist after it was added.

The code above should work, because lyr is still referring to the original ungrouped layer in that loop. Or at least, I hope so. Should be easy enough to test.

Otherwise, Dan Patterson's link is the other way, find the layer by some property other than it's name to remove it.

0 Kudos