Search code examples
pythonordereddictionary

Cannot access sub-keys in OrderedDict


I'm trying to define my ordinary dictionary as an OrderedDict, but I can't seem to access keys are the inner level.

my_dict = \
{
    'key1':
    {
        'subkey1':value1,
        'subkey2':value2
    }
}

my_ordered_dict = OrderedDict\
([(
    'key1',
    (
        ('subkey1',value1),
        ('subkey2',value2)
    )
)])

I can access ['key1'] for both cases, but I cannot access ['key1']['subkey1'] for the ordered dict.

What am I doing wrong?


Solution

  • The dictionary with 'subkey1' should also be defined as a OrderedDict ,if thats what you want. So it should be something like this

    import collections
    my_ordered_dict = collections.OrderedDict()
    sub_dict=collections.OrderedDict()
    sub_dict['subkey1']=1
    sub_dict['subkey2']=2
    my_ordered_dict['key1']=sub_dict
    sub_dict=collections.OrderedDict()
    sub_dict['subkey1']=3
    sub_dict['subkey2']=4
    my_ordered_dict['key2']=sub_dict
    print my_ordered_dict['key1']['subkey1']
    print my_ordered_dict['key2']['subkey1']
    

    The out put will be

    1
    3