Blacky Blacky - 4 months ago 11
Python Question

Trouble accessing a value from a dictionary

I have the following dictionary

Dict = {'Manu':{u'ID0020879.07': [{'ID': u'ID0020879.07', 'log': u'log-123-56', 'owner': [Manu], 'item': u'WRAITH', 'main_id': 5013L, 'status': u'noticed', 'serial': u'89980'}]}}


How can I access the serial from this dictionary?
I tried
Dict['Manu']['serial']
, But its not working as expected..
Guys any idea?

Answer

Here is the restructured dictionary.

{
    'Manu': {
        u'ID0020879.07': [{
            'ID': u'ID0020879.07',
            'log': u'log-123-56',
            'owner': [Manu],
            'item': u'WRAITH',
            'main_id': 5013L,
            'status': u'noticed',
            'serial': u'89980'
        }]
    }
}

Now, you can see where the serial key is located more clearly (not under Manu)...

It is instead

Dict['Manu']['ID0020879.07'][0]['serial']

I suggest you fix that data source to not make ID0020879.07 a key of the data (because it is duplicated in the ID key of that object in the list).

Perhaps fix like so where the Manu key maps to a list of "accounts", each with an ID and other fields

{
    'Manu': [{
        'ID': u'ID0020879.07',
        'log': u'log-123-56',
        'owner': [Manu],
        'item': u 'WRAITH',
        'main_id': 5013L,
        'status': u'noticed',
        'serial': u'89980'
    }]
}

And then you could do

Dict['Manu'][0]['serial']

Or loop the list to get all the serial keys

for item in Dict['Manu']:
    print(item['serial'])