# Using ArcGIS Field calculator with global variable?

I have an issue with creating a field calculator expression in python that utilizes global variable.

How my table looks like:

This is a fragment of road network shapefile. Each road has a code (numer), but some segments of the network have more than one code. I need to duplicate the segments that have multiple codes (already done, OrygFID is the FID of polyline from before duplicating it), assign one code per one polyline and dissolve them by their code - so I get one polyline per road.

This is how my field calculator expression looks like:

``````count = 0
globfid = ""

def function (numer, fid):
global count
global globfid

codes = numer[3:-1]
codes_s = codes.split(",")

if fid == globfid:
globfid = fid
count += 1
return codes_s[count]
else:
globfid = fid
return codes_s[count]
``````

It's supposed to clear numer from everything but the road codes (works), separate the codes into a list (works). Then it's supposed to check for OrygFID of previous row (stored as global variable), and if it's the same then it should return next code from the stored list (doesn't work). I call it using function (numer, OrygFID). The result I get for the above table is as follows (one per row).

NumerDrg: 1153K, 1147K, 1155K, 1155K.

How it should look like: 1153K, 1147K, 1155K, 1156K.

I am extremely new to Python and kind of can't wrap my head around this. Any idea why my script won't work?

• You can do this with selection sets. First select ONLY the original segments and calculate the 1st value in the list. Then select the new duplicated segments and calculate the 2nd value in the list Mar 30, 2018 at 4:22
• You are not resetting your counter in the else part. I think if you add counter =0 just before your return, it will be fine Mar 30, 2018 at 7:59

I DID IT! Thanks for suggestions, turns out the problem was that field calculator always goes by the feature id. My previous script was dependant on the sorting of table. If anyone has a similar issue - you can do it with a dictionary.

``````dict = {}

def function (numer, fid):
global dict

codes = numer[3:-1]
codes_s = codes.split(",")

if fid in dict:
dict[fid] += 1
return codes_s[dict[fid]]
else:
dict[fid] = 0
return codes_s[dict[fid]]
``````