-4

I have the following tuple list: It is for choice fields in a django model.

ENTITY_TYPE_CHOICES = (
    (0,'choice1'),
    (1,'choice2'),
)

I want to get the choices by their string name like:

entity_type_index = ENTITY_TYPE_CHOICES['choice1']

I get the error:

tuple indices must be integers, not str

Atma
  • 29,141
  • 56
  • 198
  • 299

4 Answers4

2

You can build a dictionary:

ENTITY_TYPE_CHOICES = (
(0,'choice1'),
(1,'choice2'),
)

ENTITY_TYPE_CHOICES = dict([i[::-1] for i in ENTITY_TYPE_CHOICES])

entity_type_index = ENTITY_TYPE_CHOICES['choice1']

Output:

0

If you cannot use a dictionary:

new_choice = [i[0] for i in ENTITY_TYPE_CHOICES if i[1] == 'choice1']

print new_choice[0]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

You can iterate through the tuple. Tuple objects can only be accessed by indexes, not elements (as dictionaries)

ENTITY_TYPE_CHOICES = (
    (0,'choice1'),
    (1,'choice2'),
)

choice = 0

for i in ENTITY_TYPE_CHOICES:
 if i[1] == "choice1":
  choice = i[0]

If you now print it:

print(choice)  # Output: 0

And you can now use it with choice.

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
0

You can find the index of the choice using ENTITY_TYPE_CHOICES.index('choice1')

Then you can use the number it gives to access it, by using:

 ENTITY_TYPE_CHOICES[ENTITY_TYPE_CHOICES.index('choice1')]
Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
James
  • 91
  • 8
0

Type of ENTITY_TYPE_CHOICES is tuple, but you use it as dict.

you can write method for iterate over tuple and find key:

get_entity_type_index(k):
    for index, key in ENTITY_TYPE_CHOICES:
         if key == k: return index

But this way is not the best practice.


Base on @Ajax1234 answer:

ENTITY_TYPE_CHOICES = (
   (0,'choice1'),
   (1,'choice2'),
)

ENTITY_TYPE_CHOICES_INDEX = {value: key for key, value in ENTITY_TYPE_CHOICES} 

print(ENTITY_TYPE_CHOICES_INDEX['choice2']) # output: 1
Linch
  • 511
  • 4
  • 11