Python 数据科学指南 1.3使用字典的字典

1.通过匿名函数来创建一个user_movie_rating的字典对象,以此展示“字典的字典”这一概念。

内置匿名函数 lambda,它返回一个字典。lambda : defaultdict(int) 每当又一个新的键被传递到user_movie_rating中,同时也有一个新的字典被创建。

from collections import defaultdict

user_movie_rating = defaultdict(lambda : defaultdict(int))

#
user_movie_rating["Alice"]["LOR1"]=4
user_movie_rating["Alice"]["LOR2"]=5
user_movie_rating["Alice"]["LOR3"]=3
user_movie_rating["Alice"]["SW1"]=5
user_movie_rating["Alice"]["SW2"]=3

print (user_movie_rating)

输出结果:

{'Alice': defaultdict(<class 'int'>, {'LOR1': 4, 'LOR2': 5, 'LOR3': 3, 'SW1': 5, 'SW2': 3})})

参考链接:http://www.nltk.org/book/ch05.html 下第3点“使用字典映射词到特征”,详细了解字典的使用。

猜你喜欢

转载自blog.csdn.net/cjx_cqupt/article/details/88183610