1

I want to collect data and represent it as given below, but not sure what data type to use, in case of c an multi dimension array will do the job.

                   Box 1  Box 2   Box 3     
Red                 5       8       3
Yellow              3       7       2 
Blue                5       4       9  

The number of box and the colours are not predefined. I create this by reading file box1, box2 .....

2
  • Not sure if I understand. Do you want a data structure to represent a table with markup in the cells? How do you derive the markup from the data? Commented Mar 11, 2015 at 7:48
  • can you share your code? Commented Mar 12, 2015 at 4:23

3 Answers 3

2

You can use dictionary {color : list of box count}.

e.g.

>>> colors = {}
>>> colors["red"] = [1,2,3] #you can dynamically add to list while reading files.
>>> colors["yellow"] = [0,2,4]
>>> colors 
{'yellow': [0, 2, 4], 'red': [1, 2, 3]}

then you can iterate over the dictionary and print data as you want.

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

2 Comments

It good solution if order of colours is not important. Instead need other solution.
Good solution but, the number of object in each file are not aware till i pars through the file. so i can not get do "colors["yellow"] = [0,2,4]" only after reading all files i get this information. I want to save the information just after parsing the each file.
2

@Heisenberg suggest solution with unsorted dict. But if need order of added items you can use next solution:

from collections import OrderedDict

class Colors(OrderedDict):
    """Store colors in depend from added order"""
    def __setitem__(self, color, value):
        if color in self:
            del self[color]
        OrderedDict.__setitem__(self, color, value)
colors_table = Colors()
colors_table["red"] = [1,2,3]
colors_table["yellow"] = [0,2,4]
colors_table["blue"] = [2,3,4]
print colors_table # print Colors([('red', [1, 2, 3]), ('yellow', [0, 2, 4]), ('blue', [2, 3, 4])])

1 Comment

The problem is that i do not have full information at once, I need to read the data from different files box1.txt, box2.txt & box3.txt. When i read the first file i create the dict and create the entire inforamtion, when i read second file how can i update this information ?
0

You can use multi-dimensional array in python as well, but in a slightly different manner. Here it will be an array of arrays. So your data structure will look something like:

matrix = [
    ['Color', 'Box1', 'Box2', 'Box3'],
    ['Red', 5, 8, 3],
    ['Yellow', 3, 7, 2],
    ['Blue', 5, 4, 9]
]

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.