rer49
rer49

Reputation: 235

How to pass a function argument as a key in a dictionary in Python

I am creating custom functions in which a user can specify an argument value in the custom function. The argument will be a key in a dictionary that is local to the custom function.The value associated with the key will an argument to an internal function that is nested within the custom function.

I have attached a simple example where the custom function is called Average. If I can get help on this simple example, I can use the logic to solve the more complex examples that I am working with.

# Python program to get average of a list 
def Average(lst,rnd = 'three'): 
    rndtype = {'three':3,'four':4}
    return round(sum(lst) / len(lst),rndtype[rnd].values()) 

lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst,'three') 

The error I get is the following:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-a7c034956fd8> in <module>
----> 1 average = Average(lst,'three')

<ipython-input-6-b1d1ab69b2a6> in Average(lst, rnd)
      2 def Average(lst,rnd = 'three'):
      3     rndtype = {'three':3,'four':4}
----> 4     return round(sum(lst) / len(lst),rndtype[rnd].values())

AttributeError: 'int' object has no attribute 'values'

Upvotes: 1

Views: 74

Answers (2)

Alin Ungureanu
Alin Ungureanu

Reputation: 221

The values() function applies to a dictionary, you are applying it to an element of the dictionary. You just have to remove the values() call from rndtype[rnd].

def Average(lst,rnd = 'three'): 
    rndtype = {'three':3,'four':4}
    return round(sum(lst) / len(lst),rndtype[rnd]) 

lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst,'three')

Upvotes: 2

Xhuliano Brace
Xhuliano Brace

Reputation: 119

A little confused on what you are trying to do but is this along the lines of what you are looking for? This should be right. In your parameters you should pass in just the lst and the rnd value.

# Python program to get average of a list 
def Average(lst,rnd): 
    rndtype = {'three':3,'four':4}
    return round(sum(lst)/len(lst), rndtype[rnd])

lst = [15, 10, 55, 41, 35, 20, 62, 49]
average = Average(lst,'three')

Upvotes: 2

Related Questions