2016-08-24 2 views
0

파이썬 사전에 사전 목록이 있습니다. 내가는 render_template파이썬 사전은 플라스크에서 HTML로 변환합니다.

내 사전 형식을 플라스크에 제공 할 수있는 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'}]} 

내가 키 값으로 제목과 값을 싶어요. 어떤 도움이라도 대단히 감사 할 것입니다! 가장 효율적인하지

enter image description here

+0

그냥 두 템플릿에 제어 루프를 사전에서 합격) 폐기되고있다. 사전 (키와 값을 존중히) 사전의 각 요소를 복구하기위한 첫 번째, 그리고 각 목록의 각 요소를 복구하기위한 두 번째 (가치가 전에 회복), html을 사용하여 그들을 페인트 (테이블 태그, 테이블로 포맷 된 div 적절한 방법이 될 것이다 , 테이블의 태그는 폐기되었습니다). –

답변

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

사전에서 컨트롤러로 템플릿을 전달하고 두 번 반복하십시오. 사전 (키와 값을 존중히) 사전의 각 요소를 복구하기위한 첫 번째, 그리고 각 목록의 각 요소를 복구하기위한 두 번째 (가치가 전에 회복), html을 사용하여 그들을 페인트 (테이블 태그, 테이블로 포맷 된 div 적절한 방법이 될 것입니다 , table's 태그

<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 두 열, 첫 번째 이름 목록, 두 번째 목록의 각 값을 가진 표로 칠하고 싶습니다. 첫 번째 열에는 이름 목록 (사전 키의 첫 번째 값)이 포함되어 있고 두 번째 열은 값이있는 다른 테이블 (값 이상의 루프는 목록을 의미)입니다. –

+0

감사합니다. 난 그냥 코드를 시도하고 어떤 이유로 든 다음과 같은 오류가 발생했습니다 {키 %, my_dictionary.items %의 값} TypeError : 'builtin_function_or_method'객체가 반복 가능하지 않습니다 – Pythoner1234

관련 문제