Home:ALL Converter>Pythonic way to count empty and non-empty lists in a dictionary

Pythonic way to count empty and non-empty lists in a dictionary

Ask Time:2019-08-20T10:08:33         Author:Vira

Json Formatter

I have a dictionary of lists. I want to count the number of empty and non-empty lists and print the first element of the non-empty ones at the same time.

Is there a more elegant(Python-like) way of doing it?

incorrect = 0
correct = 0
for key, l in dictionary.items():
    try:
        print(l[0])
        correct += 1
    except IndexError:
        incorrect += 1
        pass

print("Number of empty lists: ", incorrect)
print("Number of non-empty lists: ", correct)

Author:Vira,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57565866/pythonic-way-to-count-empty-and-non-empty-lists-in-a-dictionary
akiva :

Get the first non-empty item:\n\nnext(array for key, array in dictionary.items() if array) \n\n\nCount empty and none empty items:\n\ncorrect = len([array for key, array in dictionary.items() if array])\nincorrect = len([array for key, array in dictionary.items() if not array])\n",
2019-08-20T02:27:34
Omar :

A list comprehension seems like it would work well here. Assuming I've understood your question correctly you currently have a dictionary which looks something like this:\n\nlist_dict = {\"list_1\": [1], \"list_2\": [], \"list_3\": [2, 3]}\n\n\nSo you can do something like this:\n\nfirst_element_of_non_empty = [l[0] for l in list_dict.values() if l]\n\n\nHere we make use of the fact that empty lists in python evaluate to False in boolean comparisons.\n\nThen to find counts is pretty straightforward, obviously the number of non empty lists is just going to be the length of the output of the comprehension and then the empty is just the difference between this number and the total entries in the dictionary.\n\nnum_non_empty = len(first_element_of_non_empty)\nnum_empty = len(list_dict) - num_non_empty\nprint(\"Number of empty arrays: \", num_empty)\nprint(\"Number of non-empty arrays: \", num_non_empty)\n",
2019-08-20T02:19:14
yy