close

How to print Specific key value from a dictionary?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to print Specific key value from a dictionary in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to print Specific key value from a dictionary?

  1. How to print Specific key value from a dictionary?

    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.

  2. print Specific key value from a dictionary

    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.

Method 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

Method 2

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read