dreamzboy
dreamzboy

Reputation: 841

How to Find The Length of a List Containing Dictionary in Python?

I have a list of dictionary:

>>> Fruits = [{'apple': 'red', 'orange': 'orange'}, {'pear': 'green', 'cherry': 'red', 'lemon': 'yellow'}, {}, {}]
>>> 
>>> len (Fruits)
4

List 0: {'orange': 'orange', 'apple': 'red'}
List 1: {'cherry': 'red', 'lemon': 'yellow', 'pear': 'green'}
List 2: {}
List 3: {}

Although len (Fruits) does return the "correct" length, I'm wondering if there's a shortcut command only return the length of the list that has values in them?

Ultimately, I wanted to do:

# Length Fruits is expected to be 2 instead of 4.
for i in range (len (Fruits)):
    # Do something with Fruits
    Fruits [i]['grapes'] = 'purple'

Upvotes: 2

Views: 7102

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180492

You can either filter the empty dicts and check the len or simply use sum add 1 for each non empty dict:

Fruits = [{'apple': 'red', 'orange': 'orange'}, {'pear': 'green', 'cherry': 'red', 'lemon': 'yellow'}, {}, {}]

print(sum(1 for d in Fruits if d))
2

if d will evaluate to False for any empty dict so we correctly end up with 2 as the length.

If you want to remove the empty dicts from Fruits:

Fruits[:] = (d for d in Fruits if d)

print(len(Fruits))

Fruits[:] changes the original list, (d for d in Fruits if d) is a generator expression much like the sum example that only keeps the non empty dicts.

Then iterate over the list and access the dicts:

for d in Fruits:
   # do something with each dict or Fruits

Upvotes: 3

chepner
chepner

Reputation: 532093

You don't need len here at all, nor range:

for d in Fruits:
    if not d:
        continue
    # do stuff with non-empty dict d

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117981

You can filter out the empty dict entries by either:

Use a list comprehension and use the truthiness of the container (it is True iff it is non-empty)

>>> len([i for i in Fruits if i])
2

Use filter with None to filter against

>>> len(list(filter(None, Fruits)))
2

Upvotes: 2

Related Questions