2016-08-24 2 views
0

私は内部に辞書のリストを持っているpython辞書を持っています。Python辞書はフラスコのHTMLに変換する

{'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]} 

私はキーが値であることが、タイトルと値になりたい:私はrender_template

私の辞書フォーマットがあるフラスコに与えることができますHTMLテーブルにこれを変換しようとしています。どんな助けでも大いに感謝されるでしょう!最も効率的ではない

enter image description here

+0

コントローラからテンプレートへの辞書を渡し、2回ループします。最初の1つは辞書の各要素(キーと値を尊重します)を復元するためのもので、2つ目は各リストの各要素を復元するためのものです(前に復元された値)、html(tableタグ、 、テーブルのタグは廃止されています)。 –

答えて

0

しかし、あなたはただ、すでにとして、HTMLとしてレンダリング表を渡したい場合は仕事を取得します。@EliasMPさんは、テーブルの形式にお答えしようとした後

です変数をビューに追加します。より良い方法は、データだけを渡し、次にテンプレートがテンプレートロジックを使用して、必要な場所で変数をループオーバーおよび出力するようにすることです。

data = {'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]} 

table_string = '<table>' 
for key, value in data.iteritems(): 
    table_string += '<thead>' 
    table_string += '<th>' + key + '</th>' 
    table_string += '</thead>' 
    table_string += '<tbody>' 
    for i, d in enumerate(value): 
     if i == 0: 
      table_string += '<tr>' 
      for k in d.iterkeys(): 
       table_string += '<td>' + k + '</td>' 
      table_string += '</tr>' 
     table_string += '<tr>' 
     for v in d.itervalues(): 
      table_string += '<td>' + v + '</td>' 
     table_string += '</tr>' 
    table_string += '</tbody>' 
table_string += '</table>' 

print(table_string) 
1

コントローラからテンプレートへの辞書を渡して、それを2回繰り返すだけです。辞書の各要素(キーと値を尊重)を回復するための最初のものと、各リストの各要素を回復するための第2のもの(前に復元された値)、html(tableタグ、 、テーブルのタグは廃止されています)

<table> 
    <tr> 
     <th>name_of_list</th> 
     <th>values</th> 
    </tr> 

    {% for key, values in your_dictionary.items() %} 
    <tr> 
     <td>{{key}}</td> 
     <td> 
     <table> 
      <tr> 
      <th>article_title</th> 
      <th>score</th> 
      <th>type</th> 
      </tr> 
      <tr> 
      {% for articles in values %} 
       <td>{{article.article_title}}</td> 
       <td>{{article.score}}</td> 
       <td>{{article.type}}</td> 
      {% endfor %} 
      </tr> 
     </td> 
    </tr> 
    {% endfor %} 

</table> 
+0

ありがとうございました。 name_of_listと値はここで何を表していますか? – Pythoner1234

+0

Wellcome @ Pythoner1234私はあなたがそれをペイントしたいと思っていました.2つの列、最初は名前のリスト、もう1つはリストのそれぞれの値を持つテーブルです。したがって、最初の列には名前のリスト(辞書キーの最初の値)が含まれ、2番目の列にはその値を持つ別のテーブル(値のループの上にリストがあります)が入ります。 –

+0

ありがとうございます!私はちょうどコードを試して、何らかの理由で次のエラーが発生しました {キーの%、my_dictionary.items%の値} TypeError: 'builtin_function_or_method'オブジェクトは反復不可能です – Pythoner1234

関連する問題