Manish
Manish

Reputation: 2105

pythonic way to map set of strings to integers

Is there shorter way to do this?

g_proptypes = {
    'uint8' : 0
    'sint8' : 1,
    'uint16' : 2,
    'sint16' : 3,
    'uint32' : 4,
... # more strings
}

The dict is necessary as I'll have the string with me and need to find the corresponding integer.

Upvotes: 0

Views: 243

Answers (3)

pyanon
pyanon

Reputation: 1091

>>> lst = ['uint8','sint8','unit16','sint16','uint32','etc']

>>> g_proptypes = dict(map(reversed,enumerate(lst)))

>>> g_proptypes

{'sint16': 3, 'unit16': 2, 'uint8': 0, 'etc': 5, 'sint8': 1, 'uint32': 4}

Upvotes: 1

Björn Pollex
Björn Pollex

Reputation: 76828

If you have your strings in an iterable you can do:

g_proptypes = dict((string, i) for i, string in enumerate(string_list))

Upvotes: 6

DhruvPathak
DhruvPathak

Reputation: 43245

you can do this if the integers are sequential : http://codepad.org/o7ryZ09O

myList = ['uint8','sint8','uint16','sint16','uint32']
myStr = 'uint16'
myNum = myList.index(myStr);
print myNum;

Upvotes: 0

Related Questions