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.
get() method is used in Python to retrieve a value from a dictionary. dict. get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.
To print the dictionary keys in Python, use the dict. keys() method to get the keys and then use the print() function to print those keys. The dict. keys() method returns a view object that displays a list of all the keys in the dictionary.
If you only need the dictionary values -0.3246 , -0.9185 , and -3985 use: your_dict. values() . If you want both keys and values use: your_dict. items() which returns a list of tuples [(key1, value1), (key2, value2), ...] .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With