如何从嵌套字典中提取唯一值?
我想写一个函数,能列出字典里所有的值。这个列表不能有重复的项目,而且要按字母顺序排列。因为我刚开始学Python,所以我只会用iteritems()
函数来打印字典里的所有值,其他的就不知道怎么做了。
这个字典是:
critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 3.5},
'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
'Superman Returns': 3.5, 'The Night Listener': 4.0},
'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
'The Night Listener': 4.5, 'Superman Returns': 4.0,
'You, Me and Dupree': 2.5},
'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 2.0},
'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}
所以我想打印出被评分的电影列表。比如说:
《好运来临》;
《水中的女人》;
《蛇在飞机上》;
《超人归来》;
《你我与杜普里》;
等等……
有没有人能帮我一下?
2 个回答
0
另一种解决方案:
>>> reduce(lambda x,y: set(x) | set(y),[ y.keys() for y in critics.values() ])
set(['Lady in the Water', 'Snakes on a Plane', 'You, Me and Dupree', 'Just My Luck', 'Superman Returns', 'The Night Listener'])
4
最简单的方法是:
>>> d = {1: 'sadf', 2: 'sadf', 3: 'asdf'}
>>> sorted(set(d.itervalues()))
['asdf', 'sadf']
你可以按照自己的喜欢来打印。
关于你更新的问题,答案是:
>>> films = set()
>>> _ = [films.update(dic) for dic in critics.itervalues()]
>>> sorted(films)
['Just My Luck', 'Lady in the Water', 'Snakes on a Plane', 'Superman Returns', 'The Night Listener', 'You, Me and Dupree']