James Lin
James Lin

Reputation: 26528

Python: Best way to translate constants?

Background: I am adding a new function to an existing class which needs to return a list of names of constants.

Lets say I have a number of constants in a class

JOHN = 1
SMITH = 4
BEN = 8
...

And I have web service function which returns a list constant values, instead of returning [1,4,8] I would like to return more meaningful data such as ['JOHN', 'SMITH', 'BEN']

What is the efficient way to do it?

Upvotes: 1

Views: 263

Answers (1)

Silas Ray
Silas Ray

Reputation: 26150

You could use map() along with a mapping dictionary.

arg_map = {1 : 'JOHN', 4 : 'SMITH', 8 : 'BEN'}
translated_result = map(arg_map.get, result_list)

As mentioned in the comments, a list comprehension would also work here. Note you could make this a generator by replacing the square brackets with parens.

arg_map = {1 : 'JOHN', 4 : 'SMITH', 8 : 'BEN'}
translated_result = [arg_map.get(val, '%s NOT MAPPED' % str(val)) for val in result_list]

Upvotes: 3

Related Questions