码迷,mamicode.com
首页 > 编程语言 > 详细

每日python(3)

时间:2015-08-20 12:29:06      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

在读取一组数据创字典时,可以使用setdefaul函数对字典进行初始化,这样很方便呀,不用每次都检查是否为新值

比如实际任务中,我希望把以人名为key的字典改换成以movie为key的字典就可以这样写

 1 namekey_dic = {Lisa Rose: {Lady in the Water: 2.5, Snakes on a Plane: 3.5,
 2                          Just My Luck: 3.0, Superman Returns: 3.5, You, Me and Dupree: 2.5,
 3                          The Night Listener: 3.0},
 4            Gene Seymour: {Lady in the Water: 3.0, Snakes on a Plane: 3.5,
 5                             Just My Luck: 1.5, Superman Returns: 5.0, The Night Listener: 3.0,
 6                             You, Me and Dupree: 3.5},
 7            Michael Phillips: {Lady in the Water: 2.5, Snakes on a Plane: 3.0,
 8                                 Superman Returns: 3.5, The Night Listener: 4.0},
 9            Claudia Puig: {Snakes on a Plane: 3.5, Just My Luck: 3.0,
10                             The Night Listener: 4.5, Superman Returns: 4.0,
11                             You, Me and Dupree: 2.5},
12            Mick LaSalle: {Lady in the Water: 3.0, Snakes on a Plane: 4.0,
13                             Just My Luck: 2.0, Superman Returns: 3.0, The Night Listener: 3.0,
14                             You, Me and Dupree: 2.0},
15            Jack Matthews: {Lady in the Water: 3.0, Snakes on a Plane: 4.0,
16                              The Night Listener: 3.0, Superman Returns: 5.0, You, Me and Dupree: 3.5},
17            Toby: {Snakes on a Plane: 4.5, You, Me and Dupree: 1.0, Superman Returns: 4.0}
18            }
19 
20 def transform(scorelist):
21     movielist = {}
22     for person in scorelist:
23         for movie in scorelist[person]:
24             movielist.setdefault(movie, {})
25             movielist[movie][person] = scorelist[person][movie]
26     return movielist
27 
28 moviekey_dic = transform(namekey_dic)

print moviekey_dic的结果为:

1 {Lady in the Water: {Lisa Rose: 2.5, Jack Matthews: 3.0, Michael Phillips: 2.5, Gene Seymour: 3.0, Mick LaSalle: 3.0}, Snakes on a Plane: {Jack Matthews: 4.0, Mick LaSalle: 4.0, Claudia Puig: 3.5, Lisa Rose: 3.5, Toby: 4.5, Gene Seymour: 3.5, Michael Phillips: 3.0}, Just My Luck: {Claudia Puig: 3.0, Lisa Rose: 3.0, Gene Seymour: 1.5, Mick LaSalle: 2.0}, Superman Returns: {Jack Matthews: 5.0, Mick LaSalle: 3.0, Claudia Puig: 4.0, Lisa Rose: 3.5, Toby: 4.0, Gene Seymour: 5.0, Michael Phillips: 3.5}, The Night Listener: {Jack Matthews: 3.0, Mick LaSalle: 3.0, Claudia Puig: 4.5, Lisa Rose: 3.0, Gene Seymour: 3.0, Michael Phillips: 4.0}, You, Me and Dupree: {Jack Matthews: 3.5, Mick LaSalle: 2.0, Claudia Puig: 2.5, Lisa Rose: 2.5, Toby: 1.0, Gene Seymour: 3.5}}

 

每日python(3)

标签:

原文地址:http://www.cnblogs.com/ivywenyuan/p/4744460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!