kloud
kloud

Reputation: 321

How to check dictionary without values

I declared this dictionary:

person ={'name':[],'age':[], 'adress':[]}

Is there a function that allows to check if it has values or not?
For example:

person = { 'name':[], 'age':[], 'adress':[] } 

--> returns empty and if

 person = { 'name':['Paul'], 'age':[25], 'adress':['xxxxx'] }

--> returns not empty

Upvotes: 2

Views: 126

Answers (3)

Vinicius Nogueira
Vinicius Nogueira

Reputation: 59

I think that this is a solution for you, Regards

person = { 'name':[], 'age':[], 'adress':[] }

#Logical array
#True: empty fields
#False: Non empty fields
field_empty_list=[]
for field in person.keys():
    field_empty_list.append(not person[field])

# If any field is empty
any_field_is_empty = any(field_empty_list)

# If all keys are empty
all_fields_is_empty = all(field_empty_list)

Upvotes: 1

mguijarr
mguijarr

Reputation: 7910

You can do like this:

if all(person.values()):
    # not empty lists
elif not any(person.values()):
    # all empty
else:
    # some empty

Upvotes: 2

Daniel Walker
Daniel Walker

Reputation: 6750

A list will be considered truthy iff it's non-empty. That is,

if []:
    print('Yes')
else:
    print('No')

outputs No.

There's also the builtin function any which takes an iterable as an argument and returns True if any of the produced values are truthy. Therefore, if you want to know if any of the lists contain any values, you could do

any(person.values())

Upvotes: 0

Related Questions