n00bprogrammer22 n00bprogrammer22 - 20 days ago 6
Python Question

Finding value with earliest year in a dictionary

I'm writing a function where I need to search through a dictionary and return the keys and part of the value(s) that include the earliest year and if there is more then one return them as a list of tuples.

Example Dictionary:

{
'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")]
}


From this dictionary if my function was searching for the earliest year(s) it would return

earliest_year(dictionary1())

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


Three of the years "1500" were the same (and the earliest) so it returned a list of those three keys were the 1st element of the value and ignored the one with "1800". I've started working on code for this but I'm not sure how to check for the earliest year and get the error "Unexpected EOF" since I'm not asking the function to do anything yet. Any help would be appreciated

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

Answer

Try this. It first finds the minimum year and then finds all the pairs that have this minimum year.

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
Comments