-1
def wut(data):
    s = 0
    for dic in data:
        for i,value in dic.items():
            if value == "True":
                s += 1
    return s

data = [{'id': 1, 'success': True, 'name': 'Lary'},
        {'id': 2, 'success': False, 'name': 'Rabi'}, 
        {'id': 3, 'success': True, 'name': 'Alex'}]
wutewa = data
print wut(wutewa)

Hello, the code above when fed into python tutor doesn't move forward with checking if value=="True" , I'm not sure where I went wrong. I know I could use sum function but I have this thing that if I try and use as much as data structures as possible I'll be able to develop a way of thinking to code.

khelwood
  • 55,782
  • 14
  • 81
  • 108

3 Answers3

4

Should be value == True not value == "True"

Or, as Jean-François Fabre points out, simply:

if value:
     s += 1
Adelin
  • 7,809
  • 5
  • 37
  • 65
  • 1
    I was about to comment that but no, you can't do that here, as numbers and non-empty strings still evaluate to `True`. **EDIT:** To add context, the missing comment was *"or just use `if value`"*. – Nick is tired Sep 06 '17 at 13:51
  • 1
    I just deleted my comment. Shouldn't it be `value is True` in that case? (singleton, more pythonic, yes: https://stackoverflow.com/questions/4591125/is-it-safe-to-replace-with-is-to-compare-boolean-values) – Jean-François Fabre Sep 06 '17 at 13:54
  • @Jean-FrançoisFabre interesting question. Apparently it has an answer [here](https://stackoverflow.com/questions/5119709/true-and-false-in-python) – Adelin Sep 06 '17 at 13:56
  • @Jean-FrançoisFabre I'm not sure, I know `is` is considered most idomatic for `None` checks, but for booleans you might miss different identity objects like `numpy.True_` or `scipy.True_` – Chris_Rands Sep 06 '17 at 13:58
  • I'm not sure that OP wants `1==True` – Jean-François Fabre Sep 06 '17 at 13:59
1

You are comparing to string "True" instead of boolean True, you can also use an expression with built in sum() to do what you want in a more pythonic way as the following:

def wut(data):
    return sum(1 for dic in data for v in dic.values() if v is True)
Mohd
  • 5,523
  • 7
  • 19
  • 30
1

An easier way to find how many items are "truthy" values is to use list comprehension:

data = [{'id': 1, 'success': True, 'name': 'Lary'},
    {'id': 2, 'success': False, 'name': 'Rabi'}, 
    {'id': 3, 'success': True, 'name': 'Alex'}]

def wut(d):
   return sum(sum(bool(b) for b in i.values()) for i in d)

print(wut(data))

Output:

8
Ajax1234
  • 69,937
  • 8
  • 61
  • 102