How To Print Specific Key Value From A Dictionary?
Solution 1:
Python's dictionaries have no order, so indexing like you are suggesting (fruits[2]
) makes no sense as you can't 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
(don't 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
Solution 2:
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.
Solution 3:
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
Solution 4:
You can access the value of key 'kiwi' with
print(fruit['kiwi'])
Solution 5:
Is this what you are looking for?
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 in fruit:
print(fruit[key],"=",key)
Post a Comment for "How To Print Specific Key Value From A Dictionary?"