簡體   English   中英

如何遍歷python的字典列表

[英]How to iterate through a python list of dictionaries

這是我的字典:

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

我想以這種方式打印值:

-first entity
-first, second, abc

-second entity
-awe, ert

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

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

提前致謝

對於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>
for d in my_list:
    print "-%s\n-%s" % (d['entity'], ", ".join(d['place']))

首先,請注意你所謂的“我的字典”實際上是一個字典列表,我在這里調用my_list 這些詞典中的每一個都有一個'entity'鍵,易於打印。 'place'鍵有一個值列表。 我使用.join()將該列表中的所有字符串與逗號空間字符串組合在一起,以生成所需的人類可讀列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM