Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

python - How to print Specific key value from a dictionary?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...