Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if all elements of a dictionary contain the value nan? – in python

I am creating a dictionary from a dataframe. And I have two possibilities:

  • all dictionary elements come with the value "nan", like this:
bibliography_dict = {'title': nan, 'year': nan, 'authors': nan, 'pmid': nan, 'is_gwas': nan}

or

  • there is at least one element with a value other than "nan", like this ("year" element has value):
bibliography_dict = {'title': nan, 'year': 2022, 'authors': nan, 'pmid': nan, 'is_gwas': nan}

What I want is to check if all elements in this dictionary are "nan" (Null or None) and the value None should be added to an array. Otherwise, if there is at least one element with a value other than "nan", it should add the dictionary.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code:
I’m checking like this:

bibliographies = []

bibliography_empty = {"title": None,
                      "year": None,
                      "authors": None,
                      "pmid": None,
                      "is_gwas": None
                     }

if bibliography_dict == bibliography_empty:
   print("all elements are empty")
   bibliographies.append(None)
else:
   bibliographies.append(bibliography_dict)

The values of each element in the dictionary come from a dataframe. Here is the information of that dataframe:

enter image description here

Could you help me?

>Solution :

If all values of bibliography_dict are False, this will return True

all(x is None for x in bibliography_dict.values())

Example:

# Returns True
bibliography_dict = {"a": None, "b": None, "c": None}
# Retuens False
bibliography_dict = {"a": None, "b": None, "c": 2022}

Getting an an array of None

a = bibliography_dict.values()
if all(x is None for x in a):
    bibliographies = list(a)
# bibliographies will be in the form of [None, None ...]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading