访问嵌套在字典中的值

访问嵌套在字典中的值,第1张

访问嵌套字典中的值
bill_to = transactions['Transaction Details']['Bill To']

实际有效。

transactions['TransactionDetails']
是表示的表达式
dict
,因此您可以在其中进行查找。对于实际程序,我更喜欢使用面向对象的方法来嵌套字典。
collections.namedtuple
对于快速设置一堆只包含数据(而没有其自身行为)的类特别有用。

有一个警告:在某些设置中,您可能希望

KeyError
在进行查找时捕捉到该信息,并且在该设置中也可以使用,因此很难确定哪个字典查找失败:

try:    bill_to = transactions['Transaction Details']['Bill To']except KeyError:    # which of the two lookups failed?    # we don't know unless we inspect the exception;    # but it's easier to do the lookup and error handling in two steps


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5644574.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存