简体   繁体   English

计算字典字典中的值数

[英]Counting number of values in dictionaries of dictionary

I'm currently working on Enron dataset for machine learning. 我目前正在研究用于机器学习的Enron数据集。 But I'm stuck at a point where I need to find the number of NaN values for particular key in inner dictionary. 但是我陷入了需要为内部字典中的特定键找到NaN值的数量的问题。 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 . 严格来讲,我想找到工资未知的人数,即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): 假设d是包含相关值的字典的名称,并且np.nan是通过字符串'NaN'表示的(这似乎是我对Enron数据集的简要调查):

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. 我是Python的新手,我可以简单地说这是一种学习自然语言(例如说英语)的伟大语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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