如何从嵌套字典中使用Python提取唯一值?

2024-09-24 04:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢做一个函数,列出字典中所有值的列表。列表不能包含任何双重项。名单还必须按字母顺序排列。 我对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}}

所以我想打印一份被评过的电影的名单。 比如: 只是我的运气; 水中女子; 飞机上的蛇; 超人归来; 你,我和杜普利; . . . 等等。。在

有人能帮我吗?在


Tags: andtheinyouonreturnsmesnakes
2条回答

最简单的方法是:

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

随意打印。在

更新问题的答案是:

^{pr2}$

另一种解决方案:

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

相关问题 更多 >