Friday, March 21, 2014

Searching a List of Dictionaries

Often when I work in Python, I get JSON text which I convert using the JSON module in python.  This is great for me because I now have lots of data in dictionaries and lists.  Dictionaries are easy to use because everything is in a Key/Value format.  I view it as the data has nice neat labels.

Sometimes there is a need to search for data, and if that dictionary is in a list of dictionary items, how can you easily check if that item exists within a given list of dictionaries?  Enter the built-in function called any.

Python's 2.7.x help describes any as:
Return True if any element of the iterable is true. If the iterable is empty, return False.
Any it is a short cut for:
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False 

Now let's use the function.  Assume we have a given list, aListofDicts, that contains n number of dictionaries defined as such:
aListofDicts = [{"alpha": "a"}, {"alpha": "b"},
               {"alpha": "joker"},{"alpha": 1.2}]

To search this data, one would off the cuff have to write the above function to find the value in an iterable, but any gives us the magic shortcut because no one wants to write long scripts.
>>> print any(d['alpha'].lower() == 'a'.lower() for d in aListofDicts)
True
>>> print any(d['alpha'].lower() == 'tank'.lower() for d in aListofDicts)
False

So what happened in the above code?  We used generator expression, which is just a big word that creates an object that we can iterate on, ie a list.  That is this part:
aListofValues = [d for d in aListofDicts]
 Next we appends a conditional to store a list of boolean values (True/False)
aListofValues = [d[''] == "
This gives you a list of True/False values instead of a list of the actual dictionary or dictionary values.  This means if you have 1 million items in your list, you will have 1 million True/False values.  Not very efficient.

Now enters the any function:
exists = any([d['alpha'] == "
As soon as the list hit that True, if it's in position 1 or position 1 million of the list, it will stop the iteration, thus saving time and memory.  Hooray!

Happy Coding!


Wednesday, March 12, 2014

ArcGIS Pro and Python

At the Esri DevSummit 2014, it was announce that Python 3.4 will be the future of the language.

Goodbye 2.7.x and hello 3.4.

Most programmers will probably want to brush up on Python 3.x, so check out Dive into Python 3! http://getpython3.com/diveintopython3/

Enjoy


Monday, February 10, 2014

SQL Fiddle - Your Database Scratchpad

Ever want to test something out on your database but did not want to mess everything up. Now is your chance, check out: sqlfiddle.  Just go to this site and select your database.  You can then create a quick schema and dummy data and bam! Test away.


Enjoy

Tuesday, February 4, 2014

Add Geometry Attributes - ArcGIS 10.2.1 Tool

New at 10.2.1 is a simplified ways of adding geometry properties to a feature class.  The Add Geometry Attributes geoprocessing tool is a short cut from using the calculate field's geometry calculations.

Let's use the old way first:

    fc = r"some datasource"
    arcpy.AddField_management(fc, fieldName1, "DOUBLE", 
                              fieldPrecision, fieldScale)
    arcpy.AddField_management(fc, fieldName2, "DOUBLE", 
                              fieldPrecision, fieldScale)
 
    # Calculate centroid
    arcpy.CalculateField_management(fc, fieldName1, 
                                    "!SHAPE.CENTROID.X!",
                                    "PYTHON_9.3")
    arcpy.CalculateField_management(fc, fieldName2, 
                                    "!SHAPE.CENTROID.Y!",
                                    "PYTHON_9.3")
So here we create the field and then perform a calculation on the data set to get the X/Y centroid of the data.

At 10.2.1 you can clean this up and just do the following:

fc = "some dataset"
arcpy.AddGeometryAttributes_management(fc, "CENTROID")
With just two lines of code, we did what took multiple line previously to 10.2.1.

The Add Geometry Attributes tool is a time saver, and makes life just a tad easier.  It's a convenient tool that allows for quick addition of geometry attributes.

Check out more about this tool here.

Enjoy

Monday, January 13, 2014

Reading OSM Data Using Python

OpenStreetMap is a free editable community driven map.  The data can be downloaded in full from planet.openstreetmap.org, but you can also pull smaller sections from various web services.

For world pulls, I wouldn't recommend this code because you will run out of memory.  For smaller areas, same between 1-10 MB this should work depending on your desktop's specifications.


import xml
from xml.dom.minidom import parse
 
data = {}
keys = []
 
ways = {}
wkeys = []

relations = {}
rkeys = []

xmls = [r"c:\temp\small.osm"]
for f in xmls:
    dom = xml.dom.minidom.parse(f)
    #  parse out osm nodes
    #
    for n in dom.getElementsByTagName("node"):
        nid = n.getAttribute("id")
        data[nid] = {}
        data[nid]["lat"] = n.getAttribute("lat")
        data[nid]["lon"] = n.getAttribute("lon")
        for tag in n.getElementsByTagName("tag"):
            if(tag.hasAttribute("k")):
                k = tag.getAttribute("k")
                if(k not in keys):
                    keys.append(k)
                if(tag.hasAttribute("v")):
                    data[nid][k] = tag.getAttribute("v")
    # parse out osm ways/polygons
    #
    for n in dom.getElementsByTagName("way"):
        wid = n.getAttribute("id")
        ways[wid] = {}
        ways[wid]['ref'] = []
        ways[wid]['geomType'] = ""
        for nd in n.getElementsByTagName('nd'):
            if nd.hasAttribute('ref'):
                ref = nd.getAttribute('ref')
                ways[wid]['ref'].append(ref)
            del nd
        for tag in n.getElementsByTagName("tag"):
            if tag.hasAttribute("k") and \
               tag.hasAttribute('v'):
                k = tag.getAttribute("k")
                if k not in wkeys:
                    wkeys.append(k)
                ways[wid][k] = tag.getAttribute('v')
            del tag
        first = ways[wid]['ref'][0]
        last = ways[wid]['ref'][len(ways[wid]['ref'])-1]
        if ways[wid]['ref'][0] == ways[wid]['ref'][len(ways[wid]['ref'])-1]:
            ways[wid]['geomType'] = "polygon"
        else:
            ways[wid]['geomType'] = "polyline"
    for n in dom.getElementsByTagName('relation'):
        rid = n.getAttribute('id')
        relations[rid] = {}
        relations[rid]['member'] = []
        for mem in n.getElementsByTagName('member'):
            member = {}
            if mem.hasAttribtue('type'):
                member['type'] = mem.getAttribute('type')
            if mem.hasAttribute('ref'):
                member['ref'] = mem.getAttribute('ref')
            if mem.hasAttribute('role'):
                member['role'] = mem.getAttribute('role')
            relations[rid]['member'].append(member)
            del mem
        for tag in mem.getElementsByTagName("tag"):
            if tag.hasAttribute("k") and \
               tag.hasAttribute('v'):
                k = tag.getAttribute("k")
                relations[rid][k] = tag.getAttribute('v')            
            del tag
# do stuff with nodes, ways (lines), and polygons like converting the data from dictionaries to feature classes or shapefiles!

OSM files are just XML files that can be parsed with various xml processing tools in python. Some common ones are the minidom (core to python), lxml, and beautiful soup.

It is not the most efficient piece of code, but it demonstrates the power of python.

Enjoy, and feel free to make tweaks!


Thursday, January 2, 2014

Friday, December 20, 2013

Support Python GUI Support in ArcGIS

Please support my idea on having Python GUI support in ArcGIS.

http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU

I want to get this idea to over 1000 points before the beginning of 2014, and I need your help!

Thank you