2010-02-11 82 views
2

我喜欢制作一个函数,用于显示字典中所有值的列表。该列表不能包含任何双重项目。该列表还必须按字母顺序排列。 我对Python很陌生,除了使用iteritems()函数打印字典的所有值之外,我无法再进一步了。如何使用Python从嵌套字典中提取唯一值?

的字典是:

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}} 

所以我想打印已被评为电影的列表。 Like: 只是我的运气; 在水中的女士; 飞机上的蛇; 超人归来; 你,我和Dupree; 。 。 。 等等..

任何人都可以帮我吗?

回答

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'] 
+0

非常感谢了答案:d – Alphonse 2010-02-11 14:12:00

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']) 
相关问题