0

So I have a problem like this:

array_of_things = [[is_shiny=False, is_bumpy=True]
                   [is_shiny=False, is_bumpy=False]
                   [is_shiny=True, is_bumpy=True]]

To access an item, I would do this:

if array_of_things[1][1] == True: #If the second item in list is bumpy
    print("The second item is bumpy")

However, to make my code more clear, I want each item in an array to be accessed like this:

if array_of_things[1].is_bumpy == True: #If the second item in the list is bumpy
    print("The second item is bumpy")

How can I do that? Any help would be appreciated.

2
  • 1
    Have you considered using a dictionary object instead of a list inside the outer list? Commented May 20, 2016 at 2:01
  • 1
    If ordering matters you can use OrderedDict. Also take a look at namedtuple. Commented May 20, 2016 at 2:07

2 Answers 2

5

One option is using dict but if you want exactly the syntax given in your question namedtuple can be used:

from collections import namedtuple

Thing = namedtuple('Thing', ['is_shiny', 'is_bumpy'])
array_of_things = [Thing(False, True), Thing(False, False), Thing(True, True)]

if array_of_things[1].is_bumpy == True:
    print("The second item is bumpy")

namedtuple creates a new subclass of tuple which has the typename of first parameter. Fields can be accessed either with an index just like with regular tuple or with field name that was passed in a second parameter.

Sign up to request clarification or add additional context in comments.

Comments

2

If those "things" have an important meaning for your program, I'd suggest to define a class, but otherwise, use dicts:

array_of_things = [{'is_shiny': False, 'is_bumpy': True},
                   {'is_shiny': False, 'is_bumpy': False},
                   {'is_shiny': True, 'is_bumpy': True}]

if array_of_things[1]['is_bumpy']:  # since it's a boolean, no need for `==`
    print("The second item is bumpy")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.