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


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

n = {}
def dab(n):
    for key in n:
        print total


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


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


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


I actually meant to put this down

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


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


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


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