python 3.5 get value out of complicated OrderedDict

112 views Asked by At

using python 3.5, I'm reading a config file (which I have no control over) looking for a value, and it gives me back an OrderedDict. I tried:

l = list(dict.items())
for t in l:
    print(t)

that gave back a list of tuples, the value I'm looking for is in l[2] - so I went for t in l[2], that gave back another complicated output:

('driver', OrderedDict([('type', 'aws'), ('aws', 
OrderedDict([('upload_credentials', True), ('availability_zones',
OrderedDict([('eu-west-1', [OrderedDict([('zone', 'eu-west-1a'), ('subnet', 
'10.0.0.0/22')])...('ssl_cert_arn', 'arn:aws:acm:us-west-2:12345667777')]))...

here is where I got stuck, I've tried using different for looping, recursive, dict.values, etc.. but I can't reach the value I want. how can I proceed from here assuming I'm on the right track.. I'm looking for that ssl value.

1

There are 1 answers

5
Patrick Haugh On

We're just going to have to recursively scan through the OrderedDict until we see a 'ssl_cert_arn' key.

def recursive_scan(d, target):
    if target in d:
        return d[target]
    for v in d.values():
        if isinstance(v, OrderedDict):
             ret = recursive_scan(v, target)
             if ret is not None: #Maybe v[target] is some falsey value like ""
                 return ret
    return None

On further reflection, this might work even better as a generator.

def recursive_scan(d, target):
    if target in d:
        yield d[target]
    for v in d.values():
        if isinstance(v, OrderedDict):
             yield from recursive_scan(v, target)