get tuple list element by string name in python

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

4 answers

  • answered 2017-06-17 19:54 Ajax1234

    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]
    

  • answered 2017-06-17 19:54 James

    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')]
    

  • answered 2017-06-17 19:54 Linch

    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
    

  • answered 2017-06-17 19:54 Mr. Xcoder

    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.