在字典中查找最早年份的值

时间:2016-11-14 20:19:21

标签: python python-3.x dictionary numbers find

我正在编写一个函数,我需要在字典中搜索并返回包含最早年份的键和部分值,如果还有更多,则将它们作为元组列表返回

示例词典:

{
        'V':[("Self-Portrait",1500,20.0,30.0,"oil paint","Italy")],
        'B':[("Self-Portrait",1500,20.0,20.0,"oil paint","Italy")],
        'K':[("Self-Portrait-1",1500,10.0,20.0,"oil paint","Netherlands"),("Self-Portrait-2",1510,10.0,20.0,"oil paint","Netherlands"),("Self-Portrait-3",1505,10.0,20.0,"oil paint","USA")],
        'M':[("Self-Portrait-1",1800,20.0,15.0,"oil paint","USA"),("Self-Portrait-2",1801,10.0,30.0,"oil paint","France")]
        }

如果我的函数正在搜索最早的年份,那么从这本字典中可以返回

earliest_year(dictionary1())

[('B', 'Self-Portrait'), ('K', 'SelfPortrait-1'),
('V', 'Self-Portrait')]

其中三年" 1500"是相同的(也是最早的)所以它返回了这三个键的列表是值的第一个元素,并忽略了一个" 1800"。我已开始为此编写代码,但我不确定如何检查最早的年份并收到错误"意外的EOF"因为我还没有要求该功能做任何事情。任何帮助将不胜感激

def earliest_year(dictionary):   
 matches = []
 if not dictionary:
    return None
 for key in dictionary:
    for record in dictionary[key]:

2 个答案:

答案 0 :(得分:0)

试试这个。它首先找到最小年份,然后查找具有此最小年份的所有对。

def earliest_year(dictionary):
    matches = []
    min_year = min(tpl[1] for lst in dictionary.values() for tpl in lst)
    for key, lst in dictionary.items():
        for tpl in lst:
            if tpl[1] == min_year:
                matches.append((key, tpl[0]))
    return matches

答案 1 :(得分:0)

您可以将词典理解与条件列表理解结合使用:

d = {
  'B': [('Self-Portrait', 1500, 20.0, 20.0, 'oil paint', 'Italy')],
  'K': [('Self-Portrait-1', 1500, 10.0, 20.0, 'oil paint', 'Netherlands'),
        ('Self-Portrait-2', 1510, 10.0, 20.0, 'oil paint', 'Netherlands'),
        ('Self-Portrait-3', 1505, 10.0, 20.0, 'oil paint', 'USA')],
  'M': [('Self-Portrait-1', 1800, 20.0, 15.0, 'oil paint', 'USA'),
        ('Self-Portrait-2', 1801, 10.0, 30.0, 'oil paint', 'France')],
  'V': [('Self-Portrait', 1500, 20.0, 30.0, 'oil paint', 'Italy')]}
}

>>> {key: [v for v in vals if v[1] == min(v_[1] for v_ in vals)] 
     for key, vals in d.items()}
{'B': [('Self-Portrait', 1500, 20.0, 20.0, 'oil paint', 'Italy')],
 'K': [('Self-Portrait-1', 1500, 10.0, 20.0, 'oil paint', 'Netherlands')],
 'M': [('Self-Portrait-1', 1800, 20.0, 15.0, 'oil paint', 'USA')],
 'V': [('Self-Portrait', 1500, 20.0, 30.0, 'oil paint', 'Italy')]}