silver0...@gmail.com wrote: > Hi all, > > I have a understanding problem with return values from xmltodict. > > I have a xml file. Content: > > <?xml version="1.0" encoding="utf-8" ?> > <profiles> > <profile id='visio02' revision='2015051501' > > <package package-id='0964-gpg4win' /> > </profile> > </profiles> > <!-- > --> > > With code > > __f_name = '<path_to_file>' > with open(__f_name) as __fd: > __doc = xmltodict.parse(__fd.read()) > > __doc > > I get > > OrderedDict([(u'profiles', OrderedDict([(u'profile', OrderedDict([(u'@id', > u'visio02'), (u'@revision', u'2015051501'), (u'package', > OrderedDict([(u'@package-id', u'0964-gpg4win')]))]))]))]) > > If I use > > __doc['profiles']['profile']['package'][0]['@package-id'] > > I get > > Traceback (most recent call last): > File "<input>", line 1, in <module> > KeyError: 0 > > If I change xml file like this: > > <?xml version="1.0" encoding="utf-8" ?> > <profiles> > <profile id='visio02' revision='2015051501' > > <package package-id='0964-gpg4win' /> > <package package-id='0965-gpg4win' /> > </profile> > </profiles> > > and run code from above the result is: > > OrderedDict([(u'profiles', OrderedDict([(u'profile', OrderedDict([(u'@id', > u'visio02'), (u'@revision', u'2015051501'), (u'package', > [OrderedDict([(u'@package-id', u'0964-gpg4win')]), > OrderedDict([(u'@package-id', u'0965-gpg4win')])])]))]))]) > > No prints __doc['profiles']['profile']['package'][0]['@package-id']: > > u'0964-gpg4win' > > Can everybody explain this?
Not everybody, but Chris and a few others can ;) > Many thanks in advance I don't see an official way to pass a custom dict type to the library, but if you are not afraid to change its source code the following patch will allow you to access the value of dictionaries with a single entry as d[0]: $ diff -u py2b_xmltodict/local/lib/python2.7/site-packages/xmltodict.py py2_xmltodict/local/lib/python2.7/site-packages/xmltodict.py --- py2b_xmltodict/local/lib/python2.7/site-packages/xmltodict.py 2016-05-18 11:18:44.000000000 +0200 +++ py2_xmltodict/local/lib/python2.7/site-packages/xmltodict.py 2016-05-18 11:11:13.417665697 +0200 @@ -35,6 +35,13 @@ __version__ = '0.10.1' __license__ = 'MIT' +_OrderedDict = OrderedDict +class OrderedDict(_OrderedDict): + def __getitem__(self, key): + if key == 0: + [result] = self.values() + return result + return _OrderedDict.__getitem__(self, key) class ParsingInterrupted(Exception): pass -- https://mail.python.org/mailman/listinfo/python-list