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?

Asked By: otmezger

||

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.

Answered By: Martijn Pieters

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.

Answered By: John Zwinck
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.