Skip to content
Advertisement

How to print Specific key value from a dictionary?

fruit = {
    "banana": 1.00,
    "apple": 1.53,
    "kiwi": 2.00,
    "avocado": 3.23,
    "mango": 2.33,
    "pineapple": 1.44,
    "strawberries": 1.95,
    "melon": 2.34,
    "grapes": 0.98
}

for key,value in fruit.items():
     print(value)

I want to print the kiwi key, how?

print(value[2]) 

This is not working.

Advertisement

Answer

It’s too late but none of the answer mentioned about dict.get() method

>>> print(fruit.get('kiwi'))
2.0

In dict.get() method you can also pass default value if key not exist in the dictionary it will return default value. If default value is not specified then it will return None.

>>> print(fruit.get('cherry', 99))
99

fruit dictionary doesn’t have key named cherry so dict.get() method returns default value 99

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement