-1

Suppose that i have:

l = [
    ['Brasil', 'Italia', [10, 9]],
    ['Brasil', 'Espanha', [5, 7]], 
    ['Italia', 'Espanha', [7,8]],
    ]

and an empty dict:

d = {}

I'm trying to do this operation in an dict comprehension:

for x in l:
    if (x[0] not in d):
        d[x[0]] = 0
    else:
        d[x[0]] += 1

# Out: {'Brasil': 1, 'Italia': 0}

But when i try:

d = {k: (0 if (k not in d) else (d[k]+1)) for k in [x[0] for x in l]}

# Out: {'Brasil': 0, 'Italia': 0}

What an i doing wrong?

Nefisto
  • 517
  • 3
  • 9

1 Answers1

2

Better way is using Counter from collections module:

from collections import Counter

l = [
    ['Brasil', 'Italia', [10, 9]],
    ['Brasil', 'Espanha', [5, 7]], 
    ['Italia', 'Espanha', [7,8]],
    ]

c = Counter([x[0] for x in l])
c.subtract({x[0]: 1 for x in l})

print(c)
# Counter({'Brasil': 1, 'Italia': 0})
Austin
  • 25,759
  • 4
  • 25
  • 48
  • 1
    wrong output, counts are 1 higher – Chris_Rands Jan 07 '19 at 15:55
  • But i wanna to understand why it is not working, my comprehension look right for me, I need some clarify. And the out is wrong – Nefisto Jan 07 '19 at 15:56
  • @Chris_Rands, Oops. Updated mine; not sure if it's too fancy. Thanks. – Austin Jan 07 '19 at 16:02
  • I din't think that is the right way to do, subtract is rlly ugly in this code – Nefisto Jan 07 '19 at 16:04
  • well it's not ideal iterating twice, but slightly better would be `c.subtract({k:1 for k in c})` – Chris_Rands Jan 07 '19 at 16:09
  • 1
    @Chris_Rands: Easier: `c.subtract(c.keys())` (one of the few cases where calling `keys` is necessary on a `dict`, as it bypasses the path for subtracting mappings that `Counter.subtract` would otherwise use, which would reduce all counts to 0). Since it's a view though, no costly/large temporaries required. As for why the OP's code doesn't work, it's because until the `dict` comprehension is finished, the assignment to `d` doesn't happen (it constructs the new `dict` completely, then assigns), so there is no `d` (or only an old `d`) to look in. You can't reference the `dict` in progress. – ShadowRanger Jan 07 '19 at 16:17
  • @ShadowRanger thanks for your insights here and on the other post, always interesting to read – Chris_Rands Jan 07 '19 at 16:50