-3

I have a two-dimensional array, where each cell contains a dictionary that is randomly populated with a human, mosquito(es), or both. This looks like this:

{'human': Human instance, 'mosquitoes': [Mosquito instance]}

I loop through the two-dimensional array, and for every cell I check:

for row in my_array:
    for cell in row:
        if cell['human']:
            do this
        elif cell['mosquitoes']:
            do this
        elif cell[both]:
            do this

I've already tried the things suggested here, but I haven't been able to get it to work so far.

Community
  • 1
  • 1
Amos
  • 1,154
  • 1
  • 16
  • 35
  • What is an example of how "both" would look like in your dictionary? – idjaw Sep 26 '15 at 15:43
  • What error you are getting? – Rahul Gupta Sep 26 '15 at 15:44
  • You may want to somehow "keep track" of how many you encounter. How could you store a value that contains a number of occurrences? – ergonaut Sep 26 '15 at 15:45
  • Not sure if I understood the question, you want a way to test for both (if you have both keys in the dictionary)? If so `elif cell['human'] and cell['mosquitoes']:` should do the trick. – jlnabais Sep 26 '15 at 15:45
  • @RahulGupta I'm not getting an error, it just isn't working. – Amos Sep 26 '15 at 15:46
  • Its because the both check is in the elif so it never runs. make it the first if to check both, then elif check each of the human and mosquitoes – dopstar Sep 26 '15 at 15:46
  • 1
    Can you show more of your code so we can better understand the flow of your logic? – idjaw Sep 26 '15 at 15:46
  • @GingerPlusPlus it says what each cell is in my post. – Amos Sep 26 '15 at 15:57
  • @Amos: [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) – GingerPlusPlus Sep 26 '15 at 17:47
  • @GingerPlusPlus it literally says in my question that each cell is a `dict`, with 'human': `Human` and 'mosquitoes': [`Mosquito`es]. – Amos Sep 26 '15 at 17:51

2 Answers2

4

cell[both] will never run because its the last elif check. Make it the first if.

if cell['human'] and cell['mosquitoes']:
    do this
elif cell['human']:
    do this
elif cell['mosquitoes]:
    do this

Note that if either human or mosquitoes keys are not present, you might get KeyError. So you might need to use cell.get(key) syntax instead of cell[key] to cater for such events.

dopstar
  • 1,478
  • 10
  • 20
0

Did you consider trying:

if cell['mosquitoes'] and cell['human']:
    # your code goes here for this case
elif cell['mosquitoes']:
    # your code goes here for this case
elif cell['human']:
    # your code goes here for this case
Community
  • 1
  • 1