TransWikia.com

Printing only the value of a key in a dictionary

Stack Overflow Asked by Mr. Mac on December 3, 2021

I would like further explanation as to why the following code prints the value of the key. I am learning Python for a class and Zybooks is terrible at explaining.

# Complete the function to return a dictionary value
# if it exists or return Not Found if it doesn't exist
def findDictItem(mydict, key):
# Student code goes here
    if key in mydict:
        return (mydict[key])
    else:
        return 'Not Found'
# expected output: yellow
print(findDictItem({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'} , 'banana'))
# expected output: Not Found
print(findDictItem({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'},'Cameroon'))

The return(mydict[key]), in my understanding, should return the key not the value, but returns they value instead.

Would someone please provide clarity?

3 Answers

Just to make an example, there is the dictionary function get which returns a default value if the key isn't in the dictionary.

# Complete the function to return a dictionary value
# if it exists or return Not Found if it doesn't exist

def findDictItem(mydict, key):
    return mydict.get(key, 'Not found')

Answered by Chris Charley on December 3, 2021

If you want to print only the key or value, you can use something like this.

a = {'tomato': 'red', 'banana': 'yellow', 'lime': 'green'}
for key,value in a:
    print (key) #will print keys : tomato, banana, lime
    print (value) #will print values : red, yellow, green
    print (a[key]) #will print values : red, yellow, green

If you want keys, just change your code to say

if key in mydict:
    return key
else:
    return 'Not Found'

Also, you can simplify the code further.

return (key) if key in mydict else 'Not Found'

I rewrote your code as follows:

def findDictItem(mydict, key):
# Student code goes here
    return key if key in mydict else 'Not Found'
# expected output: yellow
print(findDictItem({'tomato': 'red', 'banana': 'yellow', 'lime': 'green'} , 'banana'))
# expected output: Not Found
print(findDictItem({'Brazil': 'Brasilia', 'Ireland': 'Dublin', 'Indonesia': 'Jakarta'},'Cameroon'))

Output:

banana
Not Found

Answered by Joe Ferndz on December 3, 2021

Remember that a dictionary is a map of keys to values, like

{
   'Ireland':   'Dublin',
   'Indonesia': 'Jakarta'
#   ^key         ^value
}

mydict[key] returns the value of the dictionary at index key. If you want the value of the dict at a certain key, you would use mydict[key], so mydict['Ireland'] will return Dublin.

If you just want to return Dublin, you would use return key

Answered by ACarter on December 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP