Skip to content Skip to sidebar Skip to footer

Find A Given Key's Value In A Nested Ordered Dict Python

I am trying to find the value of a given key from a nested OrderedDict. Key points: I don't know how deep this dict will be nested The name of the key I am looking for is constan

Solution 1:

If you don't know at which depth the key will appear, you will need to march through the whole dictionary.

I was so free as to convert your data to an actual ordered dictionary. The function may yield more than one result in the case that the same key appears in different sub-directories:

from collections importOrderedDictmydict= OrderedDict ( {'KYS_Q1AA_YouthSportsTrustSportParents_P':
            OrderedDict ( {'KYS_Q1AA':
                OrderedDict ( [ ('chart_layout', '3'),
                 ('client_name', 'Sport Parents (Regrouped)'),
                 ('sort_order', 'asending'),
                 ('chart_type', 'pie'),
                 ('powerpoint_color', 'blue'),
                 ('crossbreak', 'Total')
                 ] ) } ) } )

def listRecursive(d, key):
    for k, v in d.items ():
        ifisinstance(v, OrderedDict):
            for found in listRecursive(v, key):
                yield found
        ifk== key:
            yield v

for found in listRecursive(mydict, 'powerpoint_color'):
    print (found)

If you are interested in where you have found the key, you can adapt the code accordingly:

def listRecursive (d, key, path = None):
    ifnotpath: path = []
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            forpath, found in listRecursive (v, key, path + [k] ):
                yieldpath, found
        if k == key:
            yieldpath + [k], v

forpath, found in listRecursive (mydict, 'powerpoint_color'):
    print (path, found)

Solution 2:

Try this

mydict = ['KYS_Q1AA_YouthSportsTrustSportParents_P',
        ['KYS_Q1AA',
           [{'chart_layout': '3'},
            {'client_name': 'Sport Parents (Regrouped)'},
             {'sort_order': 'asending'},
             {'chart_type': 'pie'},
             {'powerpoint_color': 'blue'},
             {'crossbreak':'Total'}
             ]]]

Then...

print mydict[1][1][4]['powerpoint_color']

Solution 3:

You are looking for

print [y[1] for y in mydict[x][i]ify[0] == 'powerpoint_color']

This filters the deepest tuple to look for powerpoint_color in the first item, and keeps only the second one.

Post a Comment for "Find A Given Key's Value In A Nested Ordered Dict Python"