Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
3  
indentation as a start... – Fredrik Pihl Jun 14 at 21:25

3 Answers

up vote 5 down vote accepted

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()
    # ...
share|improve this answer

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}
share|improve this answer

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 whitespaces in string

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.