Python Forum

Full Version: Extracting results from a dictionary...
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone, I hope you are having a great day.
Here's a simple question.

I have a dictionary:
dictName = {"Jane": 90, "Max": 88, "David": 65, "Sarah": 57, "Vi": 62}
I'm trying to get a result like this:
Displaying the keys and their values, and if the value is less than 70, add "(Failed)"

Jane 90
Max 88
David 65 (Failed)
Sarah 57 (Failed)
Vi 62 (Failed)

(or in any other format that returns the same result)

This is how far I have gone!
for i in dictName.values():
    if i < 70:
        print(i, "(Failed)")
Output:
65 (Failed) 57 (Failed) 62 (Failed)
Thank you in advance for all the answers.
(Jan-11-2021, 11:38 AM)banidjamali Wrote: [ -> ]Hello everyone, I hope you are having a great day.
Here's a simple question.

I have a dictionary:
dictName = {"Jane": 90, "Max": 88, "David": 65, "Sarah": 57, "Vi": 62}
I'm trying to get a result like this:
Displaying the keys and their values, and if the value is less than 70, add "(Failed)"

Jane 90
Max 88
David 65 (Failed)
Sarah 57 (Failed)
Vi 62 (Failed)

(or in any other format that returns the same result)

This is how far I have gone!
for i in dictName.values():
    if i < 70:
        print(i, "(Failed)")
Output:
65 (Failed) 57 (Failed) 62 (Failed)
Thank you in advance for all the answers.

dictName = {"Jane": 90, "Max": 88, "David": 65, "Sarah": 57, "Vi": 62}
for i in dictName:
    print(i, dictName[i], "(Failed)" if dictName[i] < 70 else "")
(Jan-11-2021, 12:16 PM)Serafim Wrote: [ -> ]print(i, dictName[i], "(Failed)" if dictName[i] < 70 else "")
Thank you @Serafim
students = {"Jane": 90, "Max": 88, "David": 65, "Sarah": 57, "Vi": 62}
for name, grade in students.items():
    print(f'{name} {grade}{" (Failed)" if grade < 70 else ""}')
using meaningful names makes your code more readable and easy to follow. Readability counts.
Also, note that if you want to use both key and value you can iterate over dict.items(). There is also dict.keys() and dict.values(). Iterating over dict is same as dict.keys()
(Jan-11-2021, 03:59 PM)buran Wrote: [ -> ]Also, note that if you want to use both key and value you can iterate over dict.items()
Thank you! @buran