简体   繁体   中英

evaluating values of a dictionary

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?

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())

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

这个怎么样:

all(dict[k][2] is None or dict[k][2] == "" for k in dict)
reduce(lambda x,y: x and y[2] not in ('', None), d.values(), True)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM