Reputation: 307
I have a Python dictionary that I generated from an arcgis shapefile. The dictionary has key = FID (point ID) : value = either nothing or "HH". The dictionary looks like this:
Cluster_dict = {0: [u' '], 1: [u'HH'], 2: [u'HH'], 3: [u' '], 4: [u' '], 5: [u' '], 6: [u' '], 7: [u' '], 8: [u' '], 9: [u' '], 10: [u' '], 11: [u'HH'], 12: [u'HH'], 13: [u'HH'], 14: [u'HH'], 15: [u' '], 16: [u' '], 17: [u' '], 18: [u' '], 19: [u' '], 20: [u' '], 21: [u' '], 22: [u' '], 23: [u'HH'], 24: [u'HH'], 25: [u' '], 26: [u' '], 27: [u' '], 28: [u' ']....}
The extra characters of the value [u' '] and [u'HH'] show up after I created the dictionary from the arcgis shapefile with the following code:
arcpy.ClustersOutliers_stats('input_file', "GRID_CODE", 'output_file', "INVERSE_DISTANCE", "EUCLIDEAN_DISTANCE", "NONE", "", "")
Cluster_dict = {}
sc = arcpy.SearchCursor('output_file')
for row in sc:
Cluster_dict[row.FID] = [row.COType]
print Cluster_dict
I'm trying to use this dictionary to append to a nested list of each point's 8 (or less) neighbors using the following code:
clusterList = []
for clist in Neighbors_List:
row = []
for ccode in clist:
row.append(Cluster_dict[ccode])
clusterList.append(row)
print clusterList
But when it gets to row.append(Cluster_dict[ccode]), I get a key error '0'. I'm thinking this is because there is no value for key 0, but I'm not sure about this. When I used the following code to replace all the [u' '] with "None", the dictionary doesn't replace the empty values. I'm using the following code to try and replace [u' '].
for k, v in Cluster_dict.iteritems():
if v is [u' ']: #I've also tried '[u' ']'
Cluster_dict[k] = 'None'
print Cluster_dict
Any help would be appreciated. Would it be easier to strip [u' '] out of all the values in the dictionary? If so, can someone show me how to strip unwanted characters out of a dictionary?
Thanks very much for any help.
Upvotes: 2
Views: 4383
Reputation: 798636
It doesn't do what you want, use ==
instead.
Also, dict.get()
Also, '0' does not equal 0
Upvotes: 2
Reputation: 50941
Other people have told you what's wrong with using is
when you mean ==
, but you can skip that whole loop by adding some code earlier:
for row in sc:
Cluster_dict[row.FID] = [row.COType] if row.COType != u' ' else None
Upvotes: 2
Reputation: 47988
Your for loop looks good, you probably want to use ==
instead of is
to get it working. In Python the is
operator compares two objects' identities.
I do seem to be able to compare lists, contrary to one of the comments:
>>> a = [u' ']
>>> a is [u' ']
False
>>> a == [u' ']
True
Upvotes: 2