OrderedDict:无法使用键key返回d的项目.引发KeyError [英] OrderedDict: Unable Return the item of d with key key. Raises a KeyError

查看:107
本文介绍了OrderedDict:无法使用键key返回d的项目.引发KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问xmltodict转换后的值.我有一个看起来像这样的xml

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>

我正在尝试访问CASE词典.如果删除第二行XML并尝试返回d [PQ] ['CASE'],则会得到所需的结果,这是该代码:

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'])

这是d的输出的样子:

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

推荐答案

问题:无法使用键返回d的项目.引发KeyError.
我正在尝试访问CASE词典.

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


数据:

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')]))]))])

使用Python测试:3.4.2

Tested with Python: 3.4.2

这篇关于OrderedDict:无法使用键key返回d的项目.引发KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆