0

I have a dictionary where the values are a tuple

dict={'A':('1','2','3'),'B':('2','3','xxxx')....}

I need to find out if all values have a '' or None in their third element.
It just needs to be a boolean evaluation.
What is most concise way to make this happen?

This is what I did:

all(not v[2] for v in dict.values())

But i guess there will be a better 'any' form to this?

IUnknown
  • 9,301
  • 15
  • 50
  • 76
  • Could an attempt on your part be shown? – Amndeep7 Aug 07 '13 at 16:17
  • What do you mean by "'any' form"? Are you asking if there is a way to write this is with `any()` instead? It'd be `any(v[2] is not None and v[2] != '' for v in dict.values())`. By the way, if you are checking for `''` or `None` you shouldn't rely on the truthiness of these two, since you could also mistakenly evaluate the truthiness of, say, an integer or list. – 2rs2ts Aug 07 '13 at 21:04

5 Answers5

4

Python 2:

boolean = all(value[2] in ('', None) for value in your_dict.itervalues())

Python 3:

boolean = all(value[2] in ('', None) for value in your_dict.values())
JAB
  • 20,783
  • 6
  • 71
  • 80
4

You could use (Use itervalues() for Py2x)

all(elem[2] in ('', None) for elem in test.values())

See the demo -

>>> test = {'a': (1, 2, None), 'b':(2, 3, '')}
>>> all(elem[2] in ('', None) for elem in test.values())
True
>>> test['c'] = (1, 2, 3)
>>> all(elem[2] in ('', None) for elem in test.values())
False
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
  • 1
    Calling `values()` will create list of dictionary values, which could be large. `itervalues()` would be a better choice, like in @JAB's solution. – nofinator Aug 07 '13 at 19:08
  • 1
    @nofinator : My apologies. I tested this code on Py3x and completely forgot about adding itervalues. Thanks for reminding me. :) – Sukrit Kalra Aug 07 '13 at 19:20
1

How about this:

all(dict[k][2] is None or dict[k][2] == "" for k in dict)
brianmearns
  • 9,581
  • 10
  • 52
  • 79
0
reduce(lambda x,y: x and y[2] not in ('', None), d.values(), True)
Jan Matějka
  • 1,880
  • 1
  • 14
  • 31
0

Here is a simple functional solution:

not filter( lambda l : not l, [ v[2] for v in d.values()] )

It will return False if '' or None is not found in the third position, and True if one of those values is found. Partially adapted from Best way to check if a list is empty.

Community
  • 1
  • 1
Matthew Turner
  • 3,564
  • 2
  • 20
  • 21