lokheart
lokheart

Reputation: 24685

generate html table with potentially expanding columns and need to reordering columns, using django

I have created a list of dictionary in a format as below:

[{u'PLAN_A': True, u'PLAN_B': True, u'PLAN_C': True, u'PLAN_D': True, 
  u'PLAN_E': True, u'PLAN_F': True, 'date': u'2011-08-01', u'PLAN_G': True}
 {u'PLAN_A': True, u'PLAN_B': True, u'PLAN_C': True, u'PLAN_D': True, 
  u'PLAN_E': True, u'PLAN_F': True, 'date': u'2011-08-01', u'PLAN_G': True}]

A little explanation here:

The list contains information to check whether information regarding the investment plans is already provided for a particular month, if information is available, it will be TRUE, if not it will be FALSE - PLAN_A is the name of an investment plan, which means there are 7 of them here - True/False refers to whether information is entered for that particular month

I want to create a HTML output using django like the one below:

DATE    PLAN_A  PLAN_B  PLAN_C
2010-01 TRUE    FALSE   TRUE
2010-02 TRUE    FALSE   TRUE
2010-03 TRUE    FALSE   FALSE

I don't want to hard-code the column name (i.e. PLAN_A, PLAN_B, PLANC), as there maybe increasing number of plans in the future.

I think that will be a for-loop for creating <tr> and <td>. If I am working this as R, I will rearrange the column of the dataframe to the way I like (maybe I want PLAN_A to be at the third column, but not the first column), but having known that dictionary cannot be sorted, I don't know how to arrange the keys inside, as you can see in my dataset, the date key is at the 7th column.

Can anyone help? Thanks.

Upvotes: 0

Views: 158

Answers (1)

Spacedman
Spacedman

Reputation: 94307

Here's some code that given a list in the above format (with the missing comma in the right place) produces something you can work with:

bydate = []
planNames = set()
for d in data:
    ddict = {'date': d['date']}
    plans = d
    del plans['date']
    planNames = planNames.union(plans.keys())
    ddict['plans']=plans
    bydate.append(ddict)

after that, 'bydate' is:

[{'date': u'2011-08-01', 'plans': {u'PLAN_B': True, u'PLAN_C': True, u'PLAN_A': True, u'PLAN_F': True, u'PLAN_G': True, u'PLAN_D': True, u'PLAN_E': True}}, {'date': u'2011-08-22', 'plans': {u'PLAN_B': False, u'PLAN_C': True, u'PLAN_A': True, u'PLAN_F': False, u'PLAN_G': True, u'PLAN_D': True, u'PLAN_E': True}}]

which you can sort by the date key. And 'planNames' is:

set([u'PLAN_B', u'PLAN_C', u'PLAN_A', u'PLAN_F', u'PLAN_G', u'PLAN_D', u'PLAN_E'])

which is a set (like a list, but unique elements) of all the plan names mentioned in the data.

Upvotes: 1

Related Questions