Lucas
Lucas

Reputation: 1279

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?

Thanks in advance

Upvotes: 2

Views: 7781

Answers (2)

pinkdawn
pinkdawn

Reputation: 1033

for python code,

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:

<p>
{% for x in a %}
    {{x.entity}} <br/>
    {% for y in x.place %}
        {{y}}
    {% endfor %} 
    <br/>
{% endfor %}
</p>

Upvotes: 9

Ned Batchelder
Ned Batchelder

Reputation: 375724

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. Each of those dictionaries has an 'entity' key, which is easy to print. The 'place' key has a list for a value. 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.

Upvotes: 6

Related Questions