Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #108758

Re: OrderedDict

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: OrderedDict
Date 2016-05-18 20:47 +1000
Message-ID <mailman.3.1463568423.27390.python-list@python.org> (permalink)
References <7522e947-03d5-46e4-a74a-e5b312da47ad@googlegroups.com> <nhhcjb$qe6$1@ger.gmane.org> <CAPTjJmouPkqdKy3Rrtr9c+ubUjj_fQ7LdFd+ZZzoexHhnBOeNA@mail.gmail.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

OrderedDict silver0346@gmail.com - 2016-05-18 01:32 -0700
  Re: OrderedDict Chris Angelico <rosuav@gmail.com> - 2016-05-18 18:54 +1000
  Re: OrderedDict Peter Otten <__peter__@web.de> - 2016-05-18 11:28 +0200
  Re: OrderedDict Chris Angelico <rosuav@gmail.com> - 2016-05-18 20:47 +1000
  Re: OrderedDict Peter Otten <__peter__@web.de> - 2016-05-18 14:24 +0200
    Re: OrderedDict silver0346@gmail.com - 2016-05-19 22:15 -0700
      Re: OrderedDict silver0346@gmail.com - 2016-06-09 03:02 -0700

csiph-web