Iteration through Dictionaries with Lists/Tuples as stored values

05-18-2015 08:23 AM
Occasional Contributor

I currently have a nested cursor that I need to convert to one Cursor and one dictionary (or series of dictionaries) to improve performance and get a more desirable output.  I am a novice at Python coding and I am trying to understand Dictionaries.

I found that I can store a list as a dictionary value and I can call the individual entry in the value list.  For example, if D is my dictionary with keys key1 through key15 and each key is associated with a list or tuple of 5 entries for its corresponding value.  (key12 : [Name, 10, 25, 0, ABCD]).  Maybe that notation isn't 100% correct but you get the idea, hopefully.

I can call the individual entry in the list by D["key12"][4] which will return ABCD.

I have found problems when trying to iterate through these kinds of dictionaries though.  Is there a way to access the individual entries in the list/tuple during iteration or am I better off with 5 different dictionaries--one for each category in the list?

I actually have to step away from the computer so it may be a bit before I can get back to answer any questions.  I apologize.

Edit: Grammar.

0 Kudos
3 Replies
MVP Honored Contributor

Please post the script you have so far. What are the "problems" you have trying top iterate?

0 Kudos
Occasional Contributor

I figured it out in the mean time, but thank you for your response nonetheless! In case any one else new is having the same problem I am:

This is how I built the dictionary with the lists as values:

# Convert Excel constraint file to GIS table
compare = arcpy.ExcelToTable_conversion(CRIT, ProjFolder + r"\constraints")

fields = ["Rowid", "CODE", "SOIL", "MAX_SLOPE", "MIN_CDA", "MAX_CDA", "WT_SEP", "WT_RELAX",


Fields = [ for f in arcpy.ListFields(compare)]

# Create dictionary from criteria table
D = {r[1]:(r[2:]) for r in arcpy.da.SearchCursor(compare, Fields)}

The problems I was having involved trying to call the individual entries from the value list.  The first problem I had was with the following:

for r in 😧

if "A" not in r[0]:

print r

It would only print the key.  Print r[0] printed the first letter.  I couldn't seem to access the value, only the key.

But I found out that it's because "for r in D" is the same as "for r in D.keys()", so it was only looking at the keys.  So when I loop, I have to do "for k, v in D.iteritems()" or just D.items() depending on the version I'm using. 

The following code accesses the individual items stored in the value lists:

for k, v in D.iteritems():

   if "A" not in v[6]:

       print v[6]

Regular Contributor III

That iteritems has tripped me up more than once...

0 Kudos