1

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'
dreamzboy
  • 795
  • 15
  • 31
  • 1
    Do you want to operate on each dict in Fruits that is non-empty, or are you using i for something interesting? A pythonic solution depends on your intent here. Something like for `i in range( len (Fruits)); Fruits[i]['apple']` is considered an antipattern. – munk May 15 '15 at 18:08
  • possible duplicate of [Python Count Elements in a List of Objects with Matching Attributes](http://stackoverflow.com/questions/16455777/python-count-elements-in-a-list-of-objects-with-matching-attributes) – munk May 15 '15 at 18:10
  • I'm using "i" as index to add or delete dictionary values. – dreamzboy May 15 '15 at 21:51

3 Answers3

3

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • This would work but I need to iterate over the list. I would then have to use enumerate. Thank you for your help though. – dreamzboy May 15 '15 at 22:48