# ¿Cómo puedo contar las apariciones de un elemento en una lista de diccionarios?

I have a list of dictionaries (abbreviated).

``````my_list = [{ 'id':1, 'val':123 }, {'id':2, 'val':456 }, {'id':2, 'val':789 }]
``````

How can I count the occurrences of dictionaries with a specified value for a particular key (in this case '`id`')? Is there a way to leverage count (`my_list.count('id' = 1)` ?!?)

preguntado el 22 de septiembre de 13 a las 06:09

## 2 Respuestas

¿Qué tal

``````sum(1 for d in my_list if d.get('id') == the_value_you_are_interested_in)

>>> my_list = [{ 'id':1, 'val':123 }, {'id':2, 'val':456 }, {'id':2, 'val':789 }]
>>> sum(1 for d in my_list if d.get('id') == 1)
1
>>> sum(1 for d in my_list if d.get('id') == 2)
2
>>> sum(1 for d in my_list if d.get('id') == 20)
0
``````

Tenga en cuenta el uso de la generador preferible a -- of 1s. This is a pretty established technique and probably appears on several Stack Overflow questions.

I don't see any way to leverage `list.count(x)` since this method counts the number of occurrences of `x`, which in your case would be complete dictionaries. Python does have a `filter` method, but comprehensions are much preferred.

respondido 11 nov., 19:08

I do not understand your message in last line in answer - python learner. - grijesh chauhan

Si escribo `sum([1 for x in a])` y `a` is a huge list, then the list comprehension theoretically generates a huge list of 1s, THEN sums them all up. But if I write `sum(1 for x in a)` then the 1s are summed as `a` is being iterated on, without the large structure being realized. - rayo toal

Got It now! very useful information for me. Thanks you very much. - grijesh chauhan

One more thing you says "compression are preferred over `filter()`" but I read in Apress-Beginning that filter, map, reduction are much faster than list-compressions. - grijesh chauhan

@GrijeshChauhan Much faster? I don't think so. Map+filter might sometimes be faster than a comprehension, but not by much. If you have a large list use a generator instead of a comprehension in case a lazy map is the thing that is "much faster". See for example stackoverflow.com/questions/1247486/… - rayo toal

I like @Ray's answer. Another cool trick is to use `collections.Counter`.

``````from collections import Counter

c = Counter( item for dct in my_list for item in dct.items() )
c
=> Counter({('id', 2): 2, ('val', 123): 1, ('id', 1): 1, ('val', 456): 1, ('val', 789): 1})

c[('id', 2)]
=> 2
c[('id', 1)]
=> 1
c[('id', 20)]
=> 0
``````

This solution is particularly good if you need to count multiple keys/values.

If you only care about a particular key, you can do:

``````k = 'id'
id_counter = Counter( dct.get(k) for dct in my_list )
id_counter
=> Counter({2: 2, 1: 1})
id_counter[2]
=> 2
``````

Respondido el 22 de Septiembre de 13 a las 06:09

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