Python - 访问嵌套在字典中的值 [英] Python - accessing values nested within dictionaries

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

问题描述

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

  dictionary = {'ID':0001 ,'名称':'组成名称','交易':
{'交易参考':'a1','交易详情':
{'Bill To':'abc' ''''''''''''Widget A'
...} ...} ...}

目前,我正在拆包以获得ID 001的条例草案,交易参考a1如下:

  if dictionary ['ID'] == 001:
transactions = dictionary ['Transactions']
如果事务['Transaction Ref'] =='a1':
transaction_details = transactions ['Transaction Details']
bill_to = transaction_details ['Bill To']


$ b $我不禁想到这是有点笨拙,特别是最后两个李nes - 我觉得像以下这样的东西应该有效:

  bill_to =交易['交易详情'] [' Bill To'] 

是否有更简单的方法来深入嵌套字典,而无需打包到临时变量?

解决方案

  bill_to =交易['交易详情'] ['Bill To' ] 

实际工作。 事务['Transaction Details'] 是一个表示 dict 的表达式,因此您可以在其中进行查找。对于实际的方案,我宁愿使用OO方法来嵌套嵌套的dict。 collections.namedtuple 特别适用于快速设置一大堆只包含数据的类(而不是自己的行为)。


$ b有一个注意事项:在某些设置中,您可能需要在执行查找时捕获 KeyError ,而在此设置中,这也很难说明哪个字典查找失败:

  try:
bill_to = transactions ['Transaction Details'] ['Bill To']
除了KeyError:
#两个查找中哪一个失败?
#我们不知道除非我们检查异常;
#但是在两个步骤中更容易执行查找和错误处理


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'
                      ...} ...} ... }

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']

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).

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

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

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