I am trying to see how I could do this code differently


#1

I am in need of help to write this code differently in order to find { “Trevor” : 21, “Malia” : 18, }

n = {}
def dab(n):
    total=11
    for key in n:
        total+=n[key]
        print total
    dab(n)

#2

which exercise is this? This can only be a section of the section, given what you want, or not?


#3

This code is not from this section I was just using it as a base to run my code


#4

it is unclear what the code should do, it should find something, but from where of what? Please describe in detail


#5

I actually meant to put this down

n = {'Trevor' : 21, 'Malia' : 18}
def dab(n):
    total=0
    for fox in n:
        total+= n[fox]
        print total
dab(n)

#6

So that it could add 21 and 18 up to come up with 39 but I would like to find out how to make this code different and more cleaner


#7

ah, the tricky bit of optimizing code, you could do something like:

n = {'Trevor' : 21, 'Malia' : 18}
print sum([n[x] for x in n])

which is what i thought of.

then stackoverflow reminded me there is a function called values:

n = {'Trevor' : 21, 'Malia' : 18}
print sum(n.values())

values() is a build in value which will loop over the values of a dictionary, sum() is a built in function which i don't think i need to explain


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.