简体   繁体   中英

Counting number of values in dictionaries of dictionary

I'm currently working on Enron dataset for machine learning. But I'm stuck at a point where I need to find the number of NaN values for particular key in inner dictionary. This is my dictionary's sample look:

{"Name of person as a key":{"E-Mail":<email of person, if known>, "Salary":<salary off person, if known>}}

In strictly speaking, I want to find the number of people whose salary is not known, ie NaN . How should I proceed? Thanks in advance

You can do it like this:

    for person in dic:
        salary = dic.get(person).get('salary')
        if not salary:
            print person

And you get all persons whose salary is None.

Assuming that d is the name of the dictionary containing the relevant values and that np.nan is represented via the string 'NaN' (which it appears to be given my brief investigation into the Enron dataset):

count = 0
for person in d:
    if d[person].get('Salary') == 'NaN':
        count += 1

You can do like this:-

count = 0;
for key, value in dict.items():
     if(value['Salary'] is None):
             count+=1

Or

for value in dict.values():
     if(value['Salary'] is None):
             count+=1

Or in Single line:-

sum(1 for value in dict.values() if value['Salary'] is None )

Or if required to do something extra in else condition you can do like this:-

sum(1 if value['Salary'] is None else 0 for value in dict.values() )

The above line explains it in [Expression condition iteration].

One better way which gives you extra power over the counting is:- This expression return the count of salary not available:-

['salary not available' if value['Salary'] is None else ''salary available'' for value in dict.values()].count('salary not available')

And this expression return count for salary is available:-

['salary not available' if value['Salary'] is None else 'salary available' for value in dict.values()].count('salary available')

I am new in Python and I can simply say it's a great language for learning works like natural English speaking language.

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