0

I'm trying to extract only the key of an element in my dictionary but I can only figure out how to append the value.

this is my dictionary:

{"Java": 10, "Ruby": 80, "Python": 65}

I want the output to be the languages with a grade higher than 60. In this case

"Ruby", "Python"

This is my code but with the append() function, I can only extract the grade.

def my_languages(results):
    output = [] 

    for i in results:
        if results[i] >= 60:
            output.append(results[i])
    return output

Thank you all in advance

JeffC
  • 22,180
  • 5
  • 32
  • 55
HiighQ
  • 55
  • 4

2 Answers2

2

This is basic Python, please check the docs and some examples online

def my_languages(results):
    output = [] 
    for lang, grade in results.items():
        if grade >= 60:
            output.append(lang)
    return output
TheFungusAmongUs
  • 1,423
  • 3
  • 11
  • 28
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
0

When we traverse the dictionary, the key of the dictionary is index, that is, I, so you need append to be “i”.

def my_languages(results):
    output = [] 
    for i in results:
        if results[i] >= 60:
            output.append(i)
    return output
kizzy
  • 24
  • 2
  • ah yes thank you i didnt see that now is there also a quick way to sort the languages via how high the grade is? – HiighQ Jan 20 '22 at 15:31
  • @HiighQ Does [this](https://stackoverflow.com/a/613218/16177247) help? – TheFungusAmongUs Jan 20 '22 at 15:35
  • I believe alec_djinn's answer is the more standard way of iterating over a dict's keys and values. From quiet_penguin's comment on [this answer](https://stackoverflow.com/a/3294899/16177247), accessing the dict like that causes the key to be hashed again. – TheFungusAmongUs Jan 20 '22 at 15:42
  • you can sort the dict by its value, and find the first position of language:grade dict which value meet the situation , and use "output list" collect left items. – kizzy Jan 20 '22 at 15:46