Cómo iterar a través de una lista de diccionarios de Python

Este es mi diccionario:

[{'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?

Gracias por adelantado

preguntado el 04 de julio de 12 a las 02:07

2 Respuestas

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>

Respondido 04 Jul 12, 02:07

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.

Respondido 04 Jul 12, 02:07

many thanks Ned! I know you answered first, but @pinkdawn also shows the code for django template! Thanks again. - Lucas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.