2010-02-11 87 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'])