Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing nested values in nested dictionaries in Python 3.3
    primarykey
    data
    text
    <p>I'm writing in Python 3.3.</p> <p>I have a set of nested dictionaries (shown below) and am trying to search using a key at the lowest level and return each of the values that correspond to the second level.</p> <pre><code>Patients = {} Patients['PatA'] = {'c101':'AT', 'c367':'CA', 'c542':'GA'} Patients['PatB'] = {'c101':'AC', 'c367':'CA', 'c573':'GA'} Patients['PatC'] = {'c101':'AT', 'c367':'CA', 'c581':'GA'} </code></pre> <p>I'm trying to use a set of 'for loops' to search pull out the value attached to the c101 key in each Pat* dictionary nested under the main Patients dictionary.</p> <p>This is what I have so far:</p> <pre><code>pat = 'PatA' mutations = Patients[pat] for Pat in Patients.keys(): #iterate over the Pat* dictionaries for mut in Pat.keys(): #iterate over the keys in the Pat* dictionaries if mut == 'c101': #when the key in a Pat* dictionary matches 'c101' print(mut.values()) #print the value attached to the 'c101' key </code></pre> <p>I get the following error, suggesting that my for loop returns each value as a string and that this can't then be used as a dictionary key to pull out the value.</p> <blockquote> <p>Traceback (most recent call last):<br> File "filename", line 13, in <br> for mut in Pat.keys(): AttributeError: 'str' object has no attribute 'keys'</p> </blockquote> <p>I think I'm missing something obvious to do with the dictionaries class, but I can't quite tell what it is. I've had a look through <a href="https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python/636138#636138">this question</a>, but I don't think its quite what I'm asking.</p> <p>Any advice would be greatly appreciated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload