0

What's wrong with this python snippet:

for zhszam in pontok.keys():
    s = 0
    for p in pontok[zhszam]:
        if p.isdigit():
            s += int(p)
            print s
    pontok[zhszam] = s
return pontok

where pontok is {1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}. It gives the following wrong output somehow:

10
10
{1: 10, 2: 10}

While the values should be the sum of the numbers.

Thanks in advance!

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Ákos Kovács
  • 502
  • 1
  • 10
  • 23

3 Answers3

5

Every string except the first '10' has a leading space, which isn't a digit. Thus it's not being processed at all.

Try:

for p in pontok[zhszam]:
    p = p.strip()
    # ...
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

You should not use str.isdigit, it can break very easily. Better use a try-except block with int().

>>> dic = {1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}
for k,v in dic.iteritems():
    s = 0
    for x in v:
        try:
            s += int(x)     #raises Error if the item is not a valid number
        except:              
            pass            #leave the item as it is if an error was thrown
    dic[k] = s 
...     
>>> dic
{1: 35, 2: 28}
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

I'd rather comment than leave this as an answer, but I haven't the rep yet. This question will help you with stripping those leading spaces: Python remove all whitespace in a string

Community
  • 1
  • 1
Rune
  • 133
  • 7