I'm trying to loop over elements of an input string, and get them from a dictionary. What am I doing wrong?

number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 } input_str = raw_input("Enter something: ") strikes = [number_map(int(x)) for x in input_str.split()] 

strikes = [number_map(int(x)) for x in input_str.split()] TypeError: 'dict' object is not callable 
1

8 Answers

The syntax for accessing a dict given a key is number_map[int(x)]. number_map(int(x)) would actually be a function call but since number_map is not a callable, an exception is raised.

Access the dictionary with square brackets.

strikes = [number_map[int(x)] for x in input_str.split()] 

You need to use [] to access elements of a dictionary. Not ()

 number_map = { 1: -3, 2: -2, 3: -1, 4: 1, 5: 2, 6: 3 } input_str = raw_input("Enter something: ") strikes = [number_map[int(x)] for x in input_str ] 
0
strikes = [number_map[int(x)] for x in input_str.split()]

You get an element from a dict using these [] brackets, not these ().

strikes = [number_map[int(x)] for x in input_str.split()] 

Use square brackets to explore dictionaries.

You need to use:

number_map[int(x)] 

Note the square brackets!

A more functional approach would be by using dict.get

input_nums = [int(in_str) for in_str in input_str.split()) strikes = list(map(number_map.get, input_nums.split())) 

One can observe that the conversion is a little clumsy, better would be to use the abstraction of function composition:

def compose2(f, g): return lambda x: f(g(x)) strikes = list(map(compose2(number_map.get, int), input_str.split())) Example: list(map(compose2(number_map.get, int), ["1", "2", "7"])) Out[29]: [-3, -2, None] 

Obviously in Python 3 you would avoid the explicit conversion to a list. A more general approach for function composition in Python can be found here.

(Remark: I came here from the Design of Computer Programs Udacity class, to write:)

def word_score(word): "The sum of the individual letter point scores for this word." return sum(map(POINTS.get, word)) 

it's number_map[int(x)], you tried to actually call the map with one argument

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy