Python嵌套字典查找与默认值 [英] Python nested dictionary lookup with default values

查看:233
本文介绍了Python嵌套字典查找与默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> d2
{'egg': 3, 'ham': {'grill': 4, 'fry': 6, 'bake': 5}, 'spam': 2}
>>> d2.get('spamx',99)
99
>>> d2.get('ham')['fry']
6

我想获取火腿内部的鱼的价值,如果没有,得到值,99或88作为第二个例子。但是如何?

I want to get value of fry inside of ham, if not, get value, 99 or 88 as the 2nd example. But how?

推荐答案

d2.get('ham', {}).get('fry', 88)

我可能会把它分解成现实生活中的几个语句。 / p>

I would probably break it down into several statements in real life.

ham = d2.get('ham', {})
fry = ham.get('fry', 88)

这篇关于Python嵌套字典查找与默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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