Python - 访问嵌套在词典中的值

use*_*213 9 python dictionary nested

我有一个字典,其中包含字典,也可能包含字典,例如

dictionary = {'ID': 0001, 'Name': 'made up name', 'Transactions':
               {'Transaction Ref': 'a1', 'Transaction Details':
                  {'Bill To': 'abc', 'Ship To': 'def', 'Product': 'Widget A'
                      ...} ...} ... }
Run Code Online (Sandbox Code Playgroud)

目前我打开包装以获取ID 001的'Bill To','Transaction Ref'a1如下:

if dictionary['ID'] == 001:
    transactions = dictionary['Transactions']
        if transactions['Transaction Ref'] == 'a1':
            transaction_details = transactions['Transaction Details']
            bill_to = transaction_details['Bill To']
Run Code Online (Sandbox Code Playgroud)

我不禁想到这是一个有点笨重,特别是最后两行 - 我觉得下面的内容应该有效:

bill_to = transactions['Transaction Details']['Bill To']
Run Code Online (Sandbox Code Playgroud)

是否有更简单的方法可以深入到嵌套字典而无需解压缩到临时变量?

Ale*_*gov 20

你可以使用这样的东西:

>>> def lookup(dic, key, *keys):
...     if keys:
...         return lookup(dic.get(key, {}), *keys)
...     return dic.get(key)
...
>>> d = {'a':{'b':{'c':5}}}
>>> print lookup(d, 'a', 'b', 'c')
5
>>> print lookup(d, 'a', 'c')
None
Run Code Online (Sandbox Code Playgroud)

此外,如果您不想将搜索键定义为单个参数,则可以将它们作为列表传递,如下所示:

>>> print lookup(d, *['a', 'b', 'c'])
5
>>> print lookup(d, *['a', 'c'])
None
Run Code Online (Sandbox Code Playgroud)


Fre*_*Foo 14

bill_to = transactions['Transaction Details']['Bill To']
Run Code Online (Sandbox Code Playgroud)

实际上有效.transactions['Transaction Details']是表示a的表达式dict,因此您可以在其中进行查找.对于实际程序,我更喜欢OO方法来嵌套dicts.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
Run Code Online (Sandbox Code Playgroud)