I’m using a nested list to look up values in a dictionary I created. I then want to append the values found to a list. The problem I don’t know how to code is how to I keep the values appended within the same nested list structure? Here’s the code where the last line I’m appending the values to an empty list.
#Creating a dictionary of FID: LU_Codes from external txt file
import sys, arcpy, string, csv
text_file = open("H:\SWAT\NC\FID_Whole.txt", "r")
Lines = text_file.readlines()
text_file.close()
FID_LU = map(string.split, Lines)
#print FID_LU
FID_GC_dict = dict(FID_LU)
Neighbors_file = open("H:\SWAT\NC\Sh_Neighbors2.txt","r")
Entries = Neighbors_file.readlines()
Neighbors_file.close()
Neighbors_List = map(string.split, Entries)
print Neighbors_List
#FID = [x[0] for x in Neighbors_List]
#print FID
gridList = []
for list in Neighbors_List:
for item in list:
#print FID_GC_dict[item]
gridList.append(int(FID_GC_dict[item]))
print gridList
Here’s the output for Neighbors List (correct):
[['0', '1', '11', '12', '13'], ['1', '0', '2', '12', '13', '14'], ['2', '1', '3', '13', '14', '15'], ['3', '2', '4', '14', '15', '16'], ['4', '3', '5', '15', '16', '17'], ['5', '4', '6', '16', '17', '18'], ['6', '5', '7', '17', '18', '19'], ['7', '6', '8', '18', '19', '20'], ['8', '7', '9', '19', '20', '21'], ['9', '8', '20', '21', '22'], ['10', '11']]
Here’s the output for gridList (incorrect):
[3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 2, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4]
What I would like gridList to look like is:
[[3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 2], [3, 3, 3, 4, 2, 2], [3, 3, 3, 2, 2, 2], [3, 3, 3, 2, 2, 3], [3, 3, 3, 2, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3], [3, 4]]
Any help would be appreciated. I’m new to python…reading the posts helps, but I’m struggling with this one.
Thanks!
Make a temporary list,
row. Append the items from the inner loop torow, and then in the outer loop, append the row togridList:Note that you could also use a list comprehension here:
PS. It is best not to name a variable
list, since it shadows the builtin type of the same name.