首页 > 解决方案 > Python3查找pickle中的功能数量

问题描述

我读了这个适用于 Python 2 的问题,字典中的特征数量

然后我按照这个问题的解决方案,但它不起作用,TypeError:'dict_keys'对象不支持索引

如何查找每个泡菜对象中的特征数量

这是 github 存储库(如果需要),https://github.com/udacity/ud120-projects

修改后的代码/datasets_questions/explore_enron_data.py

import pickle
import pprint

enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "rb"))
pp=pprint.PrettyPrinter()
pp.pprint(enron_data)
print("Number of people:",len(enron_data))

no_of_features = len(list(enron_data.keys()))  

print("Number of features:",no_of_features)

我期望以下输出

Number of people: 146
Number of features: 21

这就是我得到的

Number of people: 146
Number of features: 146

标签: pythonpython-3.xdictionarypickle

解决方案


如果您打印所有 enron_data,您将拥有

{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', //etc

如您所见,您将名称作为键,将 {features} 作为值。这些功能也有自己的关键和价值。因此,您不能只计算 enron_data.keys() 的长度。你最好

print(len(enron_data['METTS MARK']))

输出是

21

推荐阅读