【问题标题】:Python: Find smallest values in nested dictPython:在嵌套字典中查找最小值
【发布时间】:2015-07-18 14:34:09
【问题描述】:

Python 2.7

这是Python: get key with the least value from a dictionary BUT multiple minimum values的变体

我有一本像这样的字典:

dates = {
    'first record': {
        'first date': '1985',
        'last date': '2000',
        },
    'second record': {
        'first date': '1985',
        'last date': '2012',
        },
    'third record': {
        'first date': '1985',
        'last date': '2000',
        },
    'fourth record': {
        'first date': '2000',
        'last date': '2014',
        }
}

我正在尝试检索最旧记录的键,其中最旧意味着最早的第一个日期和最早的最后一个日期。在上面的例子中,“第一条记录”和“第三条记录”都会被返回。

我很难弄清楚如何使用类似(但不太复杂)问题的答案中描述的 itervalues/iteritems 方法来实施解决方案。谁能提供一些指导?

【问题讨论】:

  • 实现一个类并重写比较魔术方法,然后对它们进行排序可能更有益。

标签: python dictionary


【解决方案1】:

你只想要钥匙:

mn_year = min((int(d['first date']), int(d['last date'])) for d in dates.values())

print(mn_year)

 print([k for k in dates
       if (int(dates[k]['first date']), int(dates[k]['last date'])) == mn_year])
(1985, 2000)
['third record', 'first record']

如果这些值不相关,则需要单独计算最小值,即:

dates = {
    'first record': {
        'first date': '1984',
        'last date': '2001',
    },
    'second record': {
        'first date': '1985',
        'last date': '2012',
    },
    'third record': {
        'first date': '1985',
        'last date': '2000',
    },
    'fourth record': {
        'first date': '2000',
        'last date': '2014',
    }
}


mn_first = min((int(d['first date'])) for d in dates.values())
mn_last = min((int(d['last date'])) for d in dates.values())


print([k for k,v in dates.iteritems()
       if int(v['first date']) == mn_first or int(v['last date']) == mn_last])

使用第一个代码返回['third record', 'first record'],而不是['first record']

获取元组的最小值不会得到每个键的最小值,而是配对元组的最小值,因此任何唯一的 first date 不一定会与最小值 last date 配对,除非最小值 last date 恰好是在同一个字典中。

我们可以使用循环同时获得两个最小值,而不是循环两次来获得最小值:

mn_first, mn_last = float("inf"),float("inf")

for d in dates.values():
    f, l = int(d['first date']),int(d['last date'])
    if f < mn_first:
        mn_first = f
    if l < mn_last:
        mn_last = l



print([k for k,v in dates.iteritems()
       if int(v['first date']) == mn_first or int(v['last date']) == mn_last])

【讨论】:

  • 列表中理解的最后一点应该是和,不是或,但这非常有效。非常感谢。
  • @AutomaticStatic,嗯,好的,所以你想要满足这两个条件的键?
  • @AutomaticStatic 是的,我认为如果它具有任何一个值,您就想要密钥,在这种情况下,如果值总是成对的,第一个代码应该按原样工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 2019-02-09
  • 2022-10-12
  • 2015-08-05
  • 2013-10-23
相关资源
最近更新 更多