2012-07-04 83 views
2

這一個Python列表迭代是我的字典:如何通過字典

[{'entity': 'first entity', 'place': ['first', 'second', 'abc']}, {'entity': 'second entity', 'place': ['awe', 'ert']}] 

,我想打印的值是這樣的:

-first entity 
-first, second, abc 

-second entity 
-awe, ert 

我嘗試了很多東西,但我不不知道如何處理第二個鍵的列表

你能否也建議我如何在Django模板中做同樣的事情?

在此先感謝

回答

9

爲Python代碼,

a = [{'entity': 'first entity', 'place': ['first', 'second', 'abc']}, {'entity': 'second entity', 'place': ['awe', 'ert']}] 
for x in a: 
    print '-', x['entity'] 
    print '-', ','.join(x['place']) 

Django的模板:

<p> 
{% for x in a %} 
    {{x.entity}} <br/> 
    {% for y in x.place %} 
     {{y}} 
    {% endfor %} 
    <br/> 
{% endfor %} 
</p> 
6
for d in my_list: 
    print "-%s\n-%s" % (d['entity'], ", ".join(d['place'])) 

首先,請注意,你叫什麼「我的字典」,實際上是字典的名單,我在這裏my_list叫。這些字典中的每一個都具有易於打印的密鑰'entity''place'鍵具有一個值列表。我使用.join()將該列表中的所有字符串與逗號空格字符串組合,以生成您想要的人類可讀列表。

+0

非常感謝斯內德!我知道你先回答,但@pinkdawn也顯示了django模板的代碼!再次感謝。 – Lucas