how I can print the values of a dictionary?

Question:

hello every one I’m trying to check a key in a dictionary and print it’s value as output. but it pass
the item and nothing won’t happen.

I write this code:

dict1={
    "apple":130,
    "avocado":50,
    "banana":110,
    "cantaloupe":50,
    "grapefruit":60,
    "grapes":90,
    "honeydew melon":50,
    "kiwifruit":90,
    "lemon":15,
    "lime":20,
    "nectarine":60,
    "orange":80,
    "peach":60,
    "pear":100,
    "pineapple":50,
    "plums":50,
    "sweet Cherries":100,
    "tangerine":50,
    "watermelon":80
}
a=input("item: ")
a=a.casefold()
for key in dict1:
    if key==a :
        print:("calories: ",str(dict1[key]))

I expect if input is apple…the output be 130 but i get ""

Asked By: Zahra Ramezani

||

Answers:

If you want to print a dict key, just use:

>>print(dict['key'])
>>'value'

For your case

print(dict1['apple'])

Should give 130 as output

Answered By: Moontasir Soumik

You don’t need a loop at all.

a=input("item: ").casefold()
print(dict1[a])
Answered By: Unmitigated

A simple way would be using the .get method on dict if the key is found it returns the corresponding value if not it returns a default value.
For your example replace the code :

for key in dict1:
if key==a :
    print:("calories: ",str(dict1[key]))

With the following code :

print:("calories: ",str(dict1.get(key, 'default-value-of-yourchoice')))
Answered By: Yassine EL baza
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.