python – How to print Specific key value from a dictionary?
python – How to print Specific key value from a dictionary?
Pythons dictionaries have no order, so indexing like you are suggesting (fruits[2]
) makes no sense as you cant retrieve the second element of something that has no order. They are merely sets of key:value
pairs.
To retrieve the value at key
: kiwi
, simply do: fruit[kiwi]
. This is the most fundamental way to access the value of a certain key. See the documentation for further clarification.
And passing that into a print()
call would actually give you an output:
print(fruit[kiwi])
#2.0
Note how the 2.00
is reduced to 2.0
, this is because superfluous zeroes are removed.
Finally, if you want to use a for-loop
(dont know why you would, they are significantly more inefficient in this case (O(n)
vs O(1)
for straight lookup)) then you can do the following:
for k, v in fruit.items():
if k == kiwi:
print(v)
#2.0
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():
if value == 2.00:
print(key)
I think you are looking for something like this.
python – How to print Specific key value from a dictionary?
Its 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 doesnt have key named cherry
so dict.get()
method returns default value 99