如何从字典中打印特定的键值? [英] How to print Specific key value from a dictionary?

查看:60
本文介绍了如何从字典中打印特定的键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fruit = {香蕉":1.00,苹果":1.53,猕猴桃":2.00,鳄梨":3.23,芒果":2.33,菠萝":1.44,草莓":1.95,甜瓜":2.34,葡萄":0.98}对于fruit.items() 中的键、值:打印(值)

我想打印奇异果钥匙,怎么办?

print(value[2])

这不起作用.

解决方案

为时已晚,但没有提到关于 dict.get() 方法

<预><代码>>>>打印(水果.get('猕猴桃'))2.0

dict.get() 方法中,您还可以传递默认值,如果字典中不存在键,它将返回默认值.如果未指定默认值,则返回 None.

<预><代码>>>>打印(水果.get('樱桃',99))99

fruit 字典没有名为 cherry 的键,所以 dict.get() 方法返回默认值 99>

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.

解决方案

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

这篇关于如何从字典中打印特定的键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆