[Tutor] updating a dictionary

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Feb 20 23:51:06 CET 2015


On 20/02/2015 17:56, Chris Stinemetz wrote:

Please don't top post as it makes long threads difficult if not 
impossible to follow, thanks.

> I am getting closer. I think I have figured out the logic. I just have a
> quick question. How do you access key:values in a nested dictionary?
>
> MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}

>
> say I want to access the key:value 8:0
>
> print dict['MOL02997_C']['8'] doesn't seem to work.

"doesn't seem to work" doesn't tell us much, so normally you would post 
your code and the full traceback that you get.  However what you have 
seems to be a dictionary that you've called dict, hence overriding the 
Python built-in name.  This isn't illegal but it's certainly frowned 
upon.  For the key 'MOL02997_C' you have a list which holds one dict 
which contains a value '8' amongst others.  Hence:-

 >>> mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}
 >>> mystruct
{'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]}
 >>> mystruct['MOL02997_C']
[{'7': '0', '8': '0', '2': '0', '9': '0'}]
 >>> mystruct['MOL02997_C'][0]
{'7': '0', '8': '0', '2': '0', '9': '0'}
 >>> mystruct['MOL02997_C'][0]['8']
'0'

Got that?

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list