Elegant way to get values in nested dictionaries for a specific key?
Question:
I have a nested dictionary in Python. I can access the A
element like this:
D[0]['detLog'][n]['A']
where n is from 0 to the length of the detLog
… In Matlab I could use something like this:
D[0]['detLog'][:]['A']
:
meaning “for all elements”.
Is there something similar in Python?
Answers:
Yes, use a list comprehension:
[d['A'] for d in D[0]['detLog']]
For scientific computing with Python, you may also want to look into NumPy and SciPy, specifically the NumPy for Matlab users documentation.
I think you want this, though it isn’t so pretty:
[x['A'] for x in D[0]['detLog'].itervalues() if 'A' in x]
What we’re doing is extracting the ‘A’ value from each dict if it exists, otherwise adding nothing to the result.
I have a nested dictionary in Python. I can access the A
element like this:
D[0]['detLog'][n]['A']
where n is from 0 to the length of the detLog
… In Matlab I could use something like this:
D[0]['detLog'][:]['A']
:
meaning “for all elements”.
Is there something similar in Python?
Yes, use a list comprehension:
[d['A'] for d in D[0]['detLog']]
For scientific computing with Python, you may also want to look into NumPy and SciPy, specifically the NumPy for Matlab users documentation.
I think you want this, though it isn’t so pretty:
[x['A'] for x in D[0]['detLog'].itervalues() if 'A' in x]
What we’re doing is extracting the ‘A’ value from each dict if it exists, otherwise adding nothing to the result.