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

蹲街弑〆低调 提交于 2019-12-13 03:43:34

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/45724345/ordereddict-unable-return-the-item-of-d-with-key-key-raises-a-keyerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!