Python Forum
Extracting results from a dictionary...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extracting results from a dictionary...
#1
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.
Reply
#2
(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 "")
banidjamali likes this post
Reply
#3
(Jan-11-2021, 12:16 PM)Serafim Wrote: print(i, dictName[i], "(Failed)" if dictName[i] < 70 else "")
Thank you @Serafim
Reply
#4
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()
banidjamali likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020