Tutorial :Format an array of tuples in a nice “table”


Say I have an array of tuples which look like that:

[('url#id1', 'url#predicate1', 'value1'),  ('url#id1', 'url#predicate2', 'value2'),  ('url#id1', 'url#predicate3', 'value3'),  ('url#id2', 'url#predicate1', 'value4'),  ('url#id2', 'url#predicate2', 'value5')]  

I would like be able to return a nice 2D array to be able to display it "as it" in my page through django.

The table would look like that:

[['', 'predicate1', 'predicate2', 'predicate3'],  ['id1', 'value1', 'value2', 'value3'],  ['id2', 'value4', 'value5', '']]  

You will notice that the 2nd item of each tuple became the table "column's title" and that we now have rows with ids and columns values.

How would you do that? Of course if you have a better idea than using the table example I gave I would be happy to have your thoughts :)

Right now I am generating a dict of dict and display that in django. But as my pairs of keys, values are not always in the same order in my dicts, then it cannot display correctly my data.



Your dict of dict is probably on the right track. While you create that dict of dict, you could also maintain a list of ids and a list of predicates. That way, you can remember the ordering and build the table by looping through those lists.

using the zip function on your initial array wil give you three lists: the list of ids, the list of predicates and the list of values.

to get rid of duplicates, try the reduce function:

list_without_duplicates = reduce(      lambda l, x: (l[-1] != x and l.append(x)) or l, list_with_duplicates, [])  



At last I came up with that code:

columns = dict()  columnsTitles = []  rows = dict()  colIdxCounter = 1 # Start with 1 because the first col are ids   rowIdxCounter = 1 # Start with 1 because the columns titles    for i in dataset:      if not rows.has_key(i[0]):          rows[i[0]] = rowIdxCounter          rowIdxCounter += 1      if not columns.has_key(i[1]):          columns[i[1]] = colIdxCounter          colIdxCounter += 1          columnsTitles.append(i[1])    toRet = [columnsTitles]  for i in range(len(rows)):      toAppend = []      for j in range(colIdxCounter):          toAppend.append("")      toRet.append(toAppend)    for i in dataset:      toRet[rows[i[0]]][columns[i[1]]] = i[2]    for i in toRet:      print i  

Please don't hesitate to comment/improve it :)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »