Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a better way to store a list of properties against one item in Python?

I am generating a list of computers attached to a server. For each computer I gather a list of properties. I am new to Python and programming and am finding my solution rather clunky.

I was doing this with lists. I have a master list: computer_list and each computer is another list, with attributes such as status, date, profile, etc.

computer_list = [cname1, cname2, cname3]
cname1 = ['online', '1/1/2012', 'desktop']

The downsides of this method are becoming obvious the more I work and change this program. I'm hoping for something more intuitive. I looked into dictionaries, but that solution seems almost as convoluted as mine. The list within a list is workable but not readable once I start iterating and assigning. I am sure there is a better way.

like image 244
pedram Avatar asked Dec 12 '25 14:12

pedram


2 Answers

Making a Computer object which stores fields describing the computer's properties and state is a viable approach.

You should read more on classes, but something like below should suit your needs:

class Computer(object):
    def __init__(self, status, date, name):
        self.status = status
        self.date = date
        self.hostname = name

    # (useful methods go here)

Perhaps you'd initialize Computer objects and store them in a list like so:

comp1 = Computer("online", "1/1/2012", "desktop")
comp2 = Computer("offline", "10/13/2012", "laptop")

computers = [comp1, comp2]
like image 178
David Cain Avatar answered Dec 14 '25 07:12

David Cain


Make each computer an object:

class Computer(object):
    def __init__(self, name, status, date, kind):
        self.name   = name
        self.status = status
        self.date   = date
        self.kind   = kind

    @classmethod    # convenience method for not repeating the name
    def new_to_dict(cls, name, status, date, kind, dictionary):
        dictionary[name] = cls(name, status, date, kind)

Then store these in a dictionary or list.

computer_list = []
computer_list.append(Computer("rainier", "online", "1/1/2012", "desktop"))

computer_dict = {}
Computer.new_to_dict("baker", "online", "1/1/2012", "laptop", computer_dict)

Now when you iterate over them, it's straightforward:

for comp in computer_list:
    print comp.name, comp.status, comp.date, comp.kind

You can also define __str__() on the class to define how they are displayed, and so on.

like image 27
kindall Avatar answered Dec 14 '25 06:12

kindall