2011-09-22 58 views
15

Django模板系统 - 如何从关键字获取python字典值?如何在django模板中获取键值?

我有两个字典代表不同的数据,但都具有相同的密钥,以便我可以从同一个密钥访问不同的数据。

首先字典是:

{**'Papa, Joey C'**: {'Office Visit Est Pt Level 3 (99213)': 32, 'LAP VENTABD HERNIA 
REPAIR (49652)': 2, 'INSERT TUNNELED CV CATH (36561)': 4, 'Office Visit New Pt 
Level 2 (99202)': 4, 'PUNCTURE/CLEAR LUNG (32420)': 1, 'REPAIR SUPERFICIAL WOUND 
S (12011)': 1, 'DEBRIDE SKINTISSUE (11042)': 29, 'Office Visit New Pt Level 3 (9 
9203)': 11, 'IDENTIFY SENTINEL NODE (38792)': 2, 'MAST MOD RAD (19307)': 1, 'EXC 
FACE LES SC < 2 CM (21011)': 1, 'ACTIVE WOUND CARE20 CM OR (97597)': 4, 'RPR UM 
BIL HERN, REDUC > 5 YR (49585)': 3, 'REMOVE LESION BACK OR FLANK (21930)': 2}} 

二字典是:

{**'Papa, Joey C'**: {'10140': 1, '10061': 1, '99214': 1, '99215': 1, '12011': 1, '97606': 1, '49080': 1, '10120': 1, '49440': 1, '49570': 1}, 'Bull, Sherman M': {'99211': 1, '99214': 1, '99215': 1, '99231': 1, '99236': 1, '12051': 1, '15004':1, '47100': 1, '15430': 1, '15431': 1}} 

Django上的模板,我用的...

{% for key1,value1 in mydict.items %} 
<br><br> 
<br><br> 
<table border="1"><tr><td>Provider Name</td><td width="70%">{{key1}}</td></tr></table> 
<br><br> 
<table class="report_by_provider"><thead><tr><th>CPT Discription</th><th>Total</th></tr></thead> 
<tbody> 
{% for key2,val2 in value1.items %} 
<tr> 
<td>{{key2}}</td> 
<td>{{val2}}</td> 
</tr> 
{% endfor %} 
</tbody> 
</table> 

<table class="report_by_provider"><thead><tr><th>CPT Code</th><th>CPT Discription</th><th>Vol</th></tr></thead> 
<tbody> 

{% for key3,val3 in mydict1.key1%} 
{% for key,val in val3.items %} 
<tr> 
<td>{{key1}}</td> 
<td>{{val}}</td> 
<td>{{val}}</td> 
</tr> 
{% endfor %} 
{% endfor %} 

但第二个字典不是印刷。

+1

可能的重复:http://stackoverflow.com/questions/2970244/django-templates-value-of-dictionary-key-with-a-space-in-it – DrTyrsa

回答

38
mydict = {'Papa, Joey C': {'10140': 1, '10061': 1, '99214': 1, '99215': 1, '12011': 1, '97606': 1, '49080': 1, '10120': 1, '49440': 1, '49570': 1}, 'Bull, Sherman M': {'99211': 1, '99214': 1, '99215': 1, '99231': 1, '99236': 1, '12051': 1, '15004':1, '47100': 1, '15430': 1, '15431': 1}} 

{% for mykey,myvalue in mydict.items %} 

    {{ mykey }} : {{ myvalue }} 

{% endfor %} 
+1

如果您只需要一个项目一个巨大的字典。 – DrTyrsa

+16

如果您只需要1个项目,您将不会首先发送字典。 –

+0

您的**评论**可能澄清了为什么我的代码很慢......大声笑 –

8

鉴于词典:

{'papa': {'name': 'Papa, Joey C', 'values': {'10140': 1, ... 

您可以使用{{ mydict1.papa.name }}

知道直接用钥匙在模板中如果包含使用空格或特价字符访问从键的值,你可以改变你的结构(就像我刚刚为这个例子做的那样)或者创建一个custom templatetag/filter,你可以像{{ mydict1|get_key:"Papa, Joey C"}}那样使用它。

如果你想要一个完整的过滤器例子,请让我知道。

+0

我需要完整的示例 –

相关问题