访问嵌套在字典中的值 [英] Accessing values nested within dictionaries
问题描述
我有一本包含字典的字典,其中可能还包含字典,例如
I have a dictionary which contains dictionaries, which may also contain dictionaries, e.g.
dictionary = {'ID': 0001, 'Name': 'made up name', 'Transactions':
{'Transaction Ref': 'a1', 'Transaction Details':
{'Bill To': 'abc', 'Ship To': 'def', 'Product': 'Widget A'
...} ...} ... }
目前,我正在打开包装以获取ID 001,交易参考" a1的付款人",如下所示:
Currently I'm unpacking to get the 'Bill To' for ID 001, 'Transaction Ref' a1 as follows:
if dictionary['ID'] == 001:
transactions = dictionary['Transactions']
if transactions['Transaction Ref'] == 'a1':
transaction_details = transactions['Transaction Details']
bill_to = transaction_details['Bill To']
我不禁觉得这有点笨拙,尤其是最后两行-我觉得以下几行应该可以工作:
I can't help but think this is is a little clunky, especially the last two lines - I feel like something along the lines of the following should work:
bill_to = transactions['Transaction Details']['Bill To']
是否有一种更简单的方法来向下钻取嵌套字典而不必解压缩临时变量?
Is there a simpler approach for drilling down into nested dictionaries without having to unpack into interim variables?
推荐答案
bill_to = transactions['Transaction Details']['Bill To']
实际上有效. transactions['Transaction Details']
是表示dict
的表达式,因此您可以在其中进行查找.对于实际程序,我更喜欢使用面向对象的方法来嵌套字典. collections.namedtuple
对于快速建立一堆只包含数据(没有自身行为)的类特别有用.
actually works. transactions['Transaction Details']
is an expression denoting a dict
, so you can do lookup in it. For practical programs, I would prefer an OO approach to nested dicts, though. collections.namedtuple
is particularly useful for quickly setting up a bunch of classes that only contain data (and no behavior of their own).
有一个警告:在某些设置中,您可能希望在执行查找时捕获KeyError
,并且在此设置中同样有效,很难确定哪个字典查找失败:
There's one caveat: in some settings, you might want to catch KeyError
when doing lookups, and in this setting, that works too, it's hard to tell which dictionary lookup failed:
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
这篇关于访问嵌套在字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!