Reputation: 75
I am using list comprehension to create a nested dictionary so that each cell in a grid has it's own copy of dictionary called stocklist...
import copy
stocklist = {'a': 0, 'b': 0, 'c': 0}
stockgrid = [[copy.deepcopy(stocklist) for w in range(WIDTH)] for h in range(HEIGHT)]
Now I will go through each element of the grid and look up items in the dictionary of each cell to compare with a value in a corresponding cell of another grid (a grid of keys)...
keygrid = [["key" for w in range(WIDTH)] for h in range(HEIGHT)]
So this is the code I have to cycle through each row and column and compare the contents in the keygrid with the contents of the matching key in the grid of stocklists, and add 1 as the value if there is a match...
for row in range(HEIGHT):
for col in range(WIDTH):
if stockgrid[row][col] == keygrid[row][col]:
stockgrid value of key in this cells dictionary = value + 1
The last line above is pure pseudo of course, I really don't know how the syntax should look though, I need the [row][col] bit to tell the computer which cell in the stockgrid I am dealing with- but then how do I tell it to +1 the value for the matching key? Hope that makes sense. In addition it may be necessary to have the "keygrid" also contain a dictionary or list of values in each cell so that more than one key can be matched in the corresponding cell of the stockgrid dictionary, the mind boggles at what the syntax of that would be! Any advise really appreciated.
Upvotes: 0
Views: 81
Reputation: 354
I suposse that keygrid is some kind of matrix in wich each element is a key of the dictionay you are making copies, am I right? Then in the stockgrid[row][col] == keygrid[row][col]
what you want to do is to look if the key of keygrid is in stockgrid and if it is true add 1 to that key value.
If that is waht you are asking the answer will be:
for row in range(HEIGHT):
for col in range(WIDTH):
if keygrid[row][col] in stockgrid[row][col]:
stockgrid[row][col][keygrid[row][col]]+=1
If inside keygrid you have a list of keys you can do this:
for row in range(HEIGHT):
for col in range(WIDTH):
# Now we select the common keys between the stockgrid and the keygrid
common_keys=[key for key in keygrid[row][col] if key in stockgrid[row][col]]
# Add one in the common_keys
for key in common_keys:
stockgrid[row][col][key]+=1
Upvotes: 1