简体   繁体   English

如何遍历python的字典列表

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

This is my dictionary: 这是我的字典:

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

and I want to print the values this way: 我想以这种方式打印值:

-first entity
-first, second, abc

-second entity
-awe, ert

I tried a lot of things but I don't know how to deal with the list of the second key 我尝试了很多东西,但我不知道如何处理第二个键的列表

Could you also suggest me how to do the same in a Django template? 你能否建议我如何在Django模板中做同样的事情?

Thanks in advance 提前致谢

for python code, 对于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'])

for django template: 对于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']))

First, note that what you called "my dictionary" is actually a list of dictionaries, I called in my_list here. 首先,请注意你所谓的“我的字典”实际上是一个字典列表,我在这里调用my_list Each of those dictionaries has an 'entity' key, which is easy to print. 这些词典中的每一个都有一个'entity'键,易于打印。 The 'place' key has a list for a value. 'place'键有一个值列表。 I use .join() to combine all the strings in that list with a comma-space string to produce the human-readable list that you want. 我使用.join()将该列表中的所有字符串与逗号空间字符串组合在一起,以生成所需的人类可读列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM