[GIS] Creating python dictionary that maps each domain to multiple coded values in File Geodatabase

arcpydictionarydomains

I have a File GDB that has domains and coded values. I would like to extract those values from the GDB and build a dictionary. For example:

I have hundreds of domains and with each domain has a set of coded values associated with it.

*Domain* , *Coded Value*
['tree', 'pine']
['tree', 'magnolia']
['tree', 'fir']
['tree', 'grey pine']
['tree', 'oak']
['soil', 'clay']
['soil', 'loam']
['soil', 'sandy']
['brush', 'manz']
['brush', 'short']
['water', 'wetland']
['water', 'lake']
etc.....

I want this:

{'tree': ['pine', 'magnolia', 'fir', 'grey pine']}
{'soil': ['clay', 'loam', 'sandy']}
{'brush': ['manz', 'short']}
{'water': ['wetland', 'lake']}

How do i accomplish this by using arcpy.da.ListDomains? This is what I have so far:

import arcpy

doms = arcpy.da.ListDomains(gdb)

    for dom in doms:

    if dom.domainType == 'CodedValue':
        codedvalues = dom.codedValues
        for code1 in codedvalues:

             list1 = []

             c_data = "{},{}".format(dom.name, code1)
             domain2 = c_data.split(",")[0]
             code2 = c_data.split(",")[1]

             list1 = [domain2, code2]
             print list1  #this prints out the first code block shown above

Best Answer

The following should do the job:

codedDomains = {domain.name: domain.codedValues.keys() for domain in arcpy.da.ListDomains(gdb) if domain.domainType == 'CodedValue'}

Basically, it uses a list comprehension to populate a dictionary, but only if it is a coded value domain. If you wanted to have it populated with the description instead of the coded value, replace the

domain.codedValues.keys()

with

domain.codedValues.values()

This entry in the ArcGIS help may also give other options on domain objects that might be helpful.