开发者

How to extract unique values from nested dictionary with Python?

I like to make a function that puts out a list of all values that are in a dictionary. The list must not contain any double items. The list also has to be in alphabetical order. I'm kind of new to Python, I can't come any further than printing all the values of the dictionary with the iteritems() function.

The dictionary is:

开发者_StackOverflow社区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}}

So I want to print a list of the movies that have been rated. Like: Just My Luck; Lady in the Water; Snakes on a Plane; Superman Returns; You, me and Dupree; . . . etcetera..

Can anybody help me out?


the simplest way would be:

>>> d = {1: 'sadf', 2: 'sadf', 3: 'asdf'}
>>> sorted(set(d.itervalues()))
['asdf', 'sadf']

print it as you like.

For your update question answer would be:

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


Another solution:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜