JavaScript
x
15
15
1
fruit = {
2
"banana": 1.00,
3
"apple": 1.53,
4
"kiwi": 2.00,
5
"avocado": 3.23,
6
"mango": 2.33,
7
"pineapple": 1.44,
8
"strawberries": 1.95,
9
"melon": 2.34,
10
"grapes": 0.98
11
}
12
13
for key,value in fruit.items():
14
print(value)
15
I want to print the kiwi key, how?
JavaScript
1
2
1
print(value[2])
2
This is not working.
Advertisement
Answer
It’s too late but none of the answer mentioned about dict.get() method
JavaScript
1
3
1
>>> print(fruit.get('kiwi'))
2
2.0
3
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
.
JavaScript
1
3
1
>>> print(fruit.get('cherry', 99))
2
99
3
fruit
dictionary doesn’t have key named cherry
so dict.get()
method returns default value 99