Search code examples
pythonpython-3.xxmltodict

OrderedDict: Unable Return the item of d with key key. Raises a KeyError


Accessing xmltodict converted values. I have an xml that looks like this

<PQ N="E90" RT="TG">
<CASES ASOF_DATE="8/11/2017" CREATE_DATE="8/13/2017" RECORDS="1130" >
<CASE>
<ID>E90</ID>

I am trying to access the CASE dictionary. If I remove the second XML line and try returning d[PQ]['CASE'], I get the desire result Here is the code for that:

def convert(xml_file, xml_attribs=True):
    with open(xml_file, "rb") as f:
        d = xmltodict.parse(f, xml_attribs=xml_attribs)
    return (d['FUND'])

This is how the output of d looks like:

OrderedDict([(PQ, OrderedDict([('@N', 'E90'), ('@RT', 'TG'), (CASES,   
OrderedDict([('@ASOF_DATE', '8/11/2017'), ('@CREATE_DATE', '8/13/2017'),  

('@RECORDS', '1130'), (CASE, [OrderedDict([('ID, E90), ..... so on

Solution

  • Question: Unable Return the item of d with key key. Raises a KeyError.
    I am trying to access the CASE dictionary.


    Data:

    od['PQ'] = \
        OrderedDict({'@N':"E90", '@RT':"TG", 'CASES':
            OrderedDict({'ASOF_DATE':"8/11/2017", 'CREATE_DATE':"8/13/2017", 'RECORDS':"1130", 'CASE':
                OrderedDict({'ID':'E90'})})})
    
    print(od['PQ'])
    >>> OrderedDict([('@N', 'E90'), ('@RT', 'TG'), ('CASES', OrderedDict([('ASOF_DATE', '8/11/2017'), ('CREATE_DATE', '8/13/2017'), ('RECORDS', '1130'), ('CASE', OrderedDict([('ID', 'E90')]))]))])
    
    print(od['PQ']['CASES'])
    >>> OrderedDict([('ASOF_DATE', '8/11/2017'), ('CREATE_DATE', '8/13/2017'), ('RECORDS', '1130'), ('CASE', OrderedDict([('ID', 'E90')]))])
    
    print(od['PQ']['CASES']['CASE'])
    >>> OrderedDict([('ID', 'E90')])
    
    print(od.get('PQ').get('CASES').get('CASE'))
    >>> OrderedDict([('ID', 'E90')])
    
    print('list(od[\'PQ\'])[2] {}'.format(list(od['PQ'].values())[2]))
    >>> list(od['PQ'])[2] OrderedDict([('ASOF_DATE', '8/11/2017'), ('CREATE_DATE', '8/13/2017'), ('RECORDS', '1130'), ('CASE', OrderedDict([('ID', 'E90')]))])
    
    for kv in list(od['PQ'].values()):
        print('od[\'PQ\'].values {}'.format(kv))
    
    >>> od['PQ'].values E90
    >>> od['PQ'].values TG
    >>> od['PQ'].values OrderedDict([('ASOF_DATE', '8/11/2017'), ('CREATE_DATE', '8/13/2017'), ('RECORDS', '1130'), ('CASE', OrderedDict([('ID', 'E90')]))])
    
    for k,v in od.items():
        print('items(od) {}:{}'.format(k,v))
    
    >>> items(od) PQ:OrderedDict([('@N', 'E90'), ('@RT', 'TG'), ('CASES', OrderedDict([('ASOF_DATE', '8/11/2017'), ('CREATE_DATE', '8/13/2017'), ('RECORDS', '1130'), ('CASE', OrderedDict([('ID', 'E90')]))]))])
    

    Tested with Python: 3.4.2