user14416782
user14416782

Reputation:

how to return certain key, value from dict and print new dict

My assessment is that I need to return the students with a grade higher than 9 in the dict_studenten_cijfers dictionary. Right now I am printing the new result but the assessment is return.

I tried it but I couldn't get it work when I tried returning it, it became a class (tuple) but it also needs to be printed out as a class dictionary.

The assessment is return the new dictionary list and print the dictionary out as class dict

def hoogvliegers(dict_studenten_cijfers):
    for key,value in dict_studenten_cijfers.items():
        if value >= 9.00:
            print(f"{key} heeft cijfer {value}.")

dict_studenten_cijfers = {
    'jonas': 9.2,
    'mustafa': 5.5,
    'mahmut': 6.0,
    'ahmed': 7.0,
    'ali': 6.0,
    'emma': 9.0,
    'klaas': 10.0,
    'pieter': 8.0,
    'peter': 7.0,
    'floris': 9.0,
    'jakob': 8.0,
    'mohammed': 10.0
}

hoogvliegers(dict_studenten_cijfers)

Upvotes: 0

Views: 55

Answers (3)

Sreeram TP
Sreeram TP

Reputation: 11927

You can use dict comprehension like this,

def hoogvliegers(d):
    # .iteritems() for python 2.x, .items() for python 3.x
    filtered_dict = {k:v for k,v in d.iteritems() if v >= 9.0}
    return filtered_dict


dict_studenten_cijfers = {
    'jonas': 9.2,
    'mustafa': 5.5,
    'mahmut': 6.0,
    'ahmed': 7.0,
    'ali': 6.0,
    'emma': 9.0,
    'klaas': 10.0,
    'pieter': 8.0,
    'peter': 7.0,
    'floris': 9.0,
    'jakob': 8.0,
    'mohammed': 10.0
}

print(hoogvliegers(dict_studenten_cijfers))

Upvotes: 1

Marius
Marius

Reputation: 94

dict_studenten_cijfers = {
'jonas': 9.2,
'mustafa': 5.5,
'mahmut': 6.0,
'ahmed': 7.0,
'ali': 6.0,
'emma': 9.0,
'klaas': 10.0,
'pieter': 8.0,
'peter': 7.0,
'floris': 9.0,
'jakob': 8.0,
'mohammed': 10.0
}
def hoogvliegers(dct):
    return {k:v for k,v in dct.items() if v>=9}

hoogvliegers(dict_studenten_cijfers)

This method uses the very handy "dict comprehension" where you iterate through each key,value pair of dct.items() and return a dictionairy, whose only values are those greater or equal than grade 9.

Output:

{'emma': 9.0, 'floris': 9.0, 'jonas': 9.2, 'mohammed': 10.0, 'klaas': 10.0}

Upvotes: 1

balderman
balderman

Reputation: 23825

Try

dict_studenten_cijfers = {
    'jonas': 9.2,
    'mustafa': 5.5,
    'mahmut': 6.0,
    'ahmed': 7.0,
    'ali': 6.0,
    'emma': 9.0,
    'klaas': 10.0,
    'pieter': 8.0,
    'peter': 7.0,
    'floris': 9.0,
    'jakob': 8.0,
    'mohammed': 10.0
}
gt_9 = [k for k,v in dict_studenten_cijfers.items() if v > 9]
print(gt_9)

output

['jonas', 'klaas', 'mohammed']

Upvotes: 1

Related Questions