gpt4 book ai didi

Python:在嵌套字典中查找最小值

转载 作者:行者123 更新时间:2023-11-28 19:18:37 25 4
gpt4 key购买 nike

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 方法来实现解决方案。谁能提供一些指导?

最佳答案

因为你只想要 key :

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

关于Python:在嵌套字典中查找最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30110910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com