Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the number of dictionaries in a python list in a loop?

I need to count how many dictionaries are in a python list so I can iterate through each? Can this be done from a for-loop . I am doing computations on each and every dictionary so need to traverse all that is available inside the list.

dataList = [{'a': 1,'b':2,'c':3}, {'a':3,'b': 3,'c':5}, {'a': 5,'b': 4,'c': 5}]

Thanks alot

like image 464
Charith Ellepola Avatar asked Oct 23 '25 18:10

Charith Ellepola


1 Answers

if you have in your list only dictionaries than you can use the buid-in function len:

len(my_list)

if you have also other objects than dictionaries in your list than you can filter your list to keep only the dictionaries in a list comprehension than use the same len method:

len([e for e in my_list if isinstance(e, dict)])

or you can use the buit-in funcion sum:

sum(1 for e in my_list if isinstance(e, dict))
like image 51
kederrac Avatar answered Oct 26 '25 10:10

kederrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!