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?
actually works.
transactions['Transaction Details']is an expression denoting adict, so you can do lookup in it. For practical programs, I would prefer an OO approach to nested dicts, though.collections.namedtupleis 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
KeyErrorwhen doing lookups, and in this setting, that works too, it’s hard to tell which dictionary lookup failed: