OrderedDict:Unable使用键键返回d项。引发KeyError

时间:2017-08-16 23:18:05

标签: python python-3.x xmltodict

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

<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] [&#39; CASE&#39;],我得到了所需的结果以下是代码:

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

1 个答案:

答案 0 :(得分:0)

  

问题:无法使用密钥返回d项。引发KeyError。
  我正在尝试访问CASE词典。

  

数据

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