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 constant, it will be somewhere in the dict
I would like to return the value of the key called "powerpoint_color" in this example...
mydict= 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')]))])),
My initial thought is to do something like this:
print mydict[x][i]['powerpoint_color']
But I get this error:
list indices must be integers, not str
Any advice?
Try this
Then...
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:
If you are interested in where you have found the key, you can adapt the code accordingly:
You are looking for
This filters the deepest tuple to look for
powerpoint_color
in the first item, and keeps only the second one.