How to convert cursor.search results into variables

1191
6
03-03-2014 03:26 AM
EdwinZea
New Contributor
Hello

I am quiet new on programing and I need some help. I want to read the values on a table a then turn them into a variable for future calculations. I have no problem with one result from the cursor.search (code bellow). But in some cases I have multiple results (up to 6) on the cursor.search. So how can I assign each of those 6 results to an independent variable ???

thanks in advance for your help

regards

EZ 8-D



 
with arcpy.da.SearchCursor(fc1, ("CountryID", "Total_Impact"), whereclause) as cursor:
    for row in cursor:
        # Access and print the row values by index position.
        #   Country name: row[0]
        #   Env Impact: row[1]
        #
        print('{0} has an impact in {1}'.format(row[0], row[1]))
        x = row[1]
Tags (2)
0 Kudos
6 Replies
JoshuaChisholm
Occasional Contributor III
Hello E.Z.

There are plenty of ways to do this in python. You could use an array of arrays, like this:

listOfRecords=[]
with arcpy.da.SearchCursor(fc1, ("CountryID", "Total_Impact"), whereclause) as cursor:
    for row in cursor:
        # Access and print the row values by index position.
        countryName: row.CountryID
        envImpact: row.Total_Impact
        print('{0} has an impact in {1}'.format(row[0], row[1]))
        listOfRecords.append([countryName,envImpact])

#access data
print "Accessing data later in the script!"
for record in listOfRecords:
    print('{0} has an impact in {1}'.format(record[0], record[1]))


However, I think a dictionary would work better for you in this case. Something like this:
countryDict={}
with arcpy.da.SearchCursor(fc1, ("CountryID", "Total_Impact"), whereclause) as cursor:
    for row in cursor:
        # Access and print the row values by index position.
        countryName: row.CountryID
        envImpact: row.Total_Impact
        print('{0} has an impact in {1}'.format(row[0], row[1]))
        countryDict[countryName]=envImpact

#access data (all records)
print "Accessing data later in the script!"
for country in sorted(countryDict): #sorted() will output the Country in alpha/numeric order
    print('{0} has an impact in {1}'.format(country, countryDict[country]))

#access data (one records)
print "Accessing one record!"
print "Canada has a Total Impact of "+str(countryDict["Canada"]) #replace "Canada" with the CountryID for Canada

NOTE: dictionaries do NOT allow duplicate keys. In this case the CountryID must be a unique field.

Let me know how it goes!
~Josh
0 Kudos
EdwinZea
New Contributor
Hey Johs thanks for the input. I kept on searching and start working with the dic idea as well.

still my problem is how to convert the values(when there is more than one) from the dic into variables??
so far I am using this code

import arcpy

arcpy.env.workspace = "D:\GIS\LCAv2.gdb"
fc1 = "D:\\GIS\\LCAv2.gdb\\houses"

def rows_as_dicts(cursor):
    colnames = cursor.fields
    for row in cursor:
        yield dict(zip(colnames, row))

# Create field name with the proper delimiters
#
whereclause = """BlockHouse > 0"""
# Use SearchCursor to access state name and the population count
#
with arcpy.da.SearchCursor(fc1, ("materials", "BlockHouse"), whereclause) as sc:
     for row in rows_as_dicts(sc):
         print row['materials']
         print row['BlockHouse']


the output is the following
Cement mortar, at plant (Plaster)
1123.2
Reinforcing steel, at plant/RER U
128.34
Lightweight concrete block, expanded clay, at plant/CH U
2106.0

my problem is how to convert the values on "BlockHouse" in to variable like:
X= 1123.2
Y = 128.34
Z = 2106.0

thanks again for any pointers

regards

EZ
0 Kudos
MathewCoyle
Frequent Contributor
So you have a field with multiple values you want to parse into individual values? Could you give us an example of some values that field may contain? Are they space, comma, something separated values? Are they geometry objects? Or something else?

Also you are using a rather odd method of accessing your row values. Is there a particular reason that you need to use the field names vs the field index to access the values?
0 Kudos
EdwinZea
New Contributor
Dear Mathew

I have a table, with several columns and rows. What I want to do is to take the values from selected cells and assign them as a variable so I can do some calculations afterwards.

In most of my cases I only need to look at one row and one column so I can get the value pretty easy.

But I have one case where I need to take the values from several rows on a column. I need to assign each of these (cell) values to a different variable. The values are like the one shown on the previous example.

I have them already on a dict, now I need is a way to convert the dict values into variable

Thanks again for the interest

regards

EZ
0 Kudos
MathewCoyle
Frequent Contributor
You can access dict values directly as a variable of sorts using the key value, or you can assign them to independent variables.

var1 = dict["key1"]
var2 = dict["key2"]
0 Kudos
JoshuaChisholm
Occasional Contributor III
Hello EZ,

I still feel a dictionary is the best solution. I'm not exact sure why you are defining a function. Perhaps I do not understand exactly what you are trying to do. I would use a dictionary like this:
import arcpy

arcpy.env.workspace = "D:\GIS\LCAv2.gdb"
fc1 = "D:\\GIS\\LCAv2.gdb\\houses"

whereclause = """BlockHouse > 0"""

dict={}

with arcpy.da.SearchCursor(fc1, ("materials", "BlockHouse"), whereclause) as sc:
    for row in sc:
        print row['materials']
        print row['BlockHouse']
        dict[row.materials]=row.BlockHouse


x=d["material 1"]
y=d["material 2"]
z=d["material 3"]

If you really want to assign your dictionary to variables (like a,b,c), you can use the exec function. I would avoid this is possible. I feel it adds a lot of unnessesary complexity. This function executes the string version of code you provide it. You could try something like this by adding it after the code above.

import string
chars=list(string.ascii_lowercase)

for i in sorted(dict):
    exec(l.pop(0)+"='"+dict+"'")

print a
print b
print c


This might suit your need, but you now don't have know good way of telling which variable (a,b,c) corresponds to which id (material). It's also hard to tell which letters were have actually been used. If you think you'll have more than 26 variables, we'll have to modify the script.
0 Kudos