0
def extract(lst,item):
    for i in lst:
        if i.get(item):
            return i[item]
print(extract([{'coin':0},{'xp':5}], 'coin'))

This code must return the value 0 as far as I understand but instead returns None. When I change the value of 0 to anything else it works correctly; looks like the only problem is that the function returns None instead of 0. The purpose of this function is to iterate through a list of dictionaries (lst) and return the value associated with the key (item).

  • 1
    Welcome to Stack Overflow. Did you consider the possibility that `i.get(item)` isn't satisfied, `for` any `i in lst`? What do you expect the code to do in that situation? Why? Now, carefully trace through what happens. What do you expect to be the result of `i.get(item)`, in the case where `i` is `{'coin': 0}` and `item` is `'coin'`? What do you expect to happen, if you test that value using `if`? Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Karl Knechtel Jun 04 '22 at 14:03
  • @DanielHao i is the index through which the for loop iterates through the lst ( which is a list of dictionaries). – Araz Sharif Jun 04 '22 at 14:04
  • Try to print `i.get(item)` - see what you got? – Daniel Hao Jun 04 '22 at 14:04
  • Just try put this line `only` after your `for-loop`: `return d.get(item, None)` – Daniel Hao Jun 04 '22 at 14:09
  • 1
    @DanielHao Thanks I don't understand how, but this worked! I still don't know what the problem was though haha! – Araz Sharif Jun 04 '22 at 14:16
  • The issues is here - `if i.get(item)` return found `0` right? In Python `0` is considered `False`. As the link points out. In other words, next line/statement will Never got exeuted. – Daniel Hao Jun 04 '22 at 14:19

0 Answers0