OrderedDict

Chris Angelico rosuav at gmail.com
Wed May 18 06:47:01 EDT 2016


On Wed, May 18, 2016 at 7:28 PM, Peter Otten <__peter__ at web.de> wrote:
> 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

Easier than patching might be monkeypatching.

class OrderedDict(OrderedDict):
    ... getitem code as above ...
xmltodict.OrderedDict = OrderedDict

Try it, see if it works.

ChrisA



More information about the Python-list mailing list