简体   繁体   中英

Python data structures, dictionary?

I hope somebody can help. I am using Python and I would like to be able to do the following.

I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or integers

For example the shape 'Rectangle' may have the following commands
'ChangeColor' 'green'
'FillStyle' 'hatch'
'Dimensions' 10 15
etc.....

What would be the best data structure to store this information. I need to be able to easily retrieve these commands from the data structure given the 'shape' of the object. Would a dictionary be the correct choice, I have never used these before

Thanks

You might be better off creating your own class:

class Shape(object):
    def __init__(self):
        self.shape = "rectangle"
        self.color = "green"
        self.fillstyle = "hatch"
        # etc

    def ChangeColor(self, color):
        self.color = color

    # etc

dicts are for when the order isn't important but you want store values for different names.

lists are ordered sequences of objects, usually of the same type and the position doesn't mean anything particular.

tuples are ordered sequences of objects, possibly of different types and each different position has a specific meaning.

I would suggest using an object class and storing all of the values/commands within that object so that you can pass it around easily. (Similar to what recursive said).

However; you could also use a dictionary with the key being the object name and the values being a list containing possible commands.

It seems to me that a command could be represented as a list [] or tuple () , and so could a series of commands. So one possibility is that you have a list of lists of strings. Generally you want to use a dictionary only when you want to look up a value by key. For example, if you knew the name of a command (wrt a shape) and wanted to know which parameters were passed to that command, you could have a dictionary mapping from string to list.

If you post more about how you plan to use this data, I could give a better answer.

Here is a link to the Python documentation on basic data structures, which should be very helpful: http://docs.python.org/tutorial/datastructures.html

Edit : in response to first comment, do you need to store the commands or just read them from input one by one and execute them?

What about this?

Example

s = {'Rectangle':
        {'ChangeColor':'green','FillStyle':'hatch',
         'Dimension1': 10, 'Dimension2':15}}
s['Triangle'] = {'ChangeColor':'red','FillStyle':'hatch',
         'Dimension1': 10, 'Dimension2':15, 'Dimension3':5}

for k, v in s.iteritems():
    print k
    for k1, v1 in v.iteritems():
        print "   ", k1, "=", v1

Result:

Triangle
    Dimension1 = 10
    Dimension2 = 15
    Dimension3 = 5
    ChangeColor = red
    FillStyle = hatch
Rectangle
    Dimension1 = 10
    Dimension2 = 15
    ChangeColor = green
    FillStyle = hatch

I would store the commands as a list of lists, or of tuples, depending on whether or not I thought I'd modify commands. Note that argument unpacking in Python makes for a very simple mechanism for executing these commands, eg:

class Shape(object):
    def background(self, color):
        print "background:", color
    def foreground(self, color):
        print "foreground:", color
    def rect(self, left, top, right, bottom):
        print "rect:", left, top, right, bottom
    def execute_commands(self, command_list):
        for command in command_list:
            if hasattr(self, command[0]):
                getattr(self, command[0])(*command[1:])

>>> s = Shape()
>>> c = [('background', 'blue'), ('foreground', 'yellow'), ('rect', 10, 0, 20, 20)]
>>> s.execute_commands(c)
background: blue
foreground: yellow
rect: 10 0 20 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM