0

Create a function called get_laureates() that thas three parameters:dict_prizes (positional parameter) year (keyword parameter with default None) category (keyword parameter with default None)

The function should find all laureates that received the Nobel Prize, optionally in a specific year and/or category (specified using the keywords year and category). It should return a list of the full names of the laureates.

For example, for the year 2018 and category "peace" it should return the list ['Denis Mukwege', 'Nadia Murad'].

f = open('/content/laureate.json')
  
dict_laureates = json.load(f)

def get_laureates(year, category):
    for element in dict_laureates['laureates']:
        for k in element['prizes']:
            if (k['category'])  == category and k['year'] == year:
            
                return (element['firstname'] + " "+ element['surname'])
                   

get_laureates(year = "2005", category = "chemistry")

it does not work when there are more than 1 output. Any ideas on how to fix this?

however it does not work if there are more than 1 output. Any idea how to modify the code that it outputs all with given criteria?

Thomas
  • 9
  • 2

1 Answers1

0

it does not work when there are more than 1 output.

For sure! Have you ever heard of the keyword yield?

Just replace return with yield, and the function will give you back all the names with a tuple.


To convert a generator to a list, simply use list function.

result = list(get_laureates(year="2005", category="chemistry"))

If you want to iterate on the generator, simply don't convert it and use the for ... in syntax.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28