【问题标题】:How to extract unique values from nested dictionary with Python?如何使用 Python 从嵌套字典中提取唯一值?
【发布时间】:2010-02-11 13:49:36
【问题描述】:

我喜欢创建一个函数来列出字典中所有值的列表。该列表不得包含任何双重项目。该列表还必须按字母顺序排列。 我是 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}}

所以我想打印一份已评分的电影列表。 喜欢: 只是我的运气; 水中的女士; 飞机上的蛇; 超人归来; 你、我和杜普里; . . . 等等……

谁能帮帮我?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    最简单的方法是:

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

    【讨论】:

      【解决方案2】:

      另一种解决方案:

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

      【讨论】:

        猜你喜欢
        • 2017-03-29
        • 1970-01-01
        • 2022-01-09
        • 2015-11-28
        • 2021-04-19
        • 1970-01-01
        • 1970-01-01
        • 2013-08-09
        • 2021-06-02
        相关资源
        最近更新 更多