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


Groups > comp.lang.python > #110475 > unrolled thread

I seem to be creating a dict that I cannot access the keys of

Started bySayth Renshaw <flebber.crue@gmail.com>
First post2016-06-23 20:59 -0700
Last post2016-06-27 09:08 +0200
Articles 4 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  I seem to be creating a dict that I cannot access the keys of Sayth Renshaw <flebber.crue@gmail.com> - 2016-06-23 20:59 -0700
    Re: I seem to be creating a dict that I cannot access the keys of dieter <dieter@handshake.de> - 2016-06-25 09:50 +0200
      Re: I seem to be creating a dict that I cannot access the keys of Sayth Renshaw <flebber.crue@gmail.com> - 2016-06-25 01:41 -0700
        Re: I seem to be creating a dict that I cannot access the keys of dieter <dieter@handshake.de> - 2016-06-27 09:08 +0200

#110475 — I seem to be creating a dict that I cannot access the keys of

FromSayth Renshaw <flebber.crue@gmail.com>
Date2016-06-23 20:59 -0700
SubjectI seem to be creating a dict that I cannot access the keys of
Message-ID<8c9b5b13-c6cc-458d-9d31-56f7e5db10c4@googlegroups.com>
Really getting a little lost here with lxml.

I cannot seem to create a dict of results using xpath or other that I could easily get the results from, currently I am always returned a printed copy of the whole file regardless of what parsing options I do.

Can I ask is there something obvious wrong, i have left the commented other versions in they "work" in that they all produce the same output the print whole file.


def parseXML():
    """
    given a file XML will parse for listed attributes.

    using objectified lxml
    """
    for file in getsMeet(file_list):
        with open(file, "rb") as f:
            xml = f.read()
            root = objectify.parse(xml)
            atts = ("number", "id", "horse", "saddlecloth", "barrier",
                    "weight", "rating", "description", "colours", "owners",
                    "dob", "age", "sex", "career", "thistrack", "thisdistance",
                    "goodtrack", "heavytrack", "finished", "weightvariation",
                    "variedweight", "decimalmargin", "penalty",
                    "pricestarting")

            tree = etree.parse(StringIO(xml))
            result = etree.tostring(tree.getroot(), pretty_print=True)
            for sample in result:
                noms = (dict(zip(atts, map(sample.attrib.get, atts))))
                print(noms)
            # print(etree.tostring(tree.getroot()))
            #
            # for sample in root.xpath('//race/nomination'):
            #     noms = (dict(zip(atts, map(sample.attrib.get, atts))))
            #     numbers = [(k, v) for k, v in noms.items()]
            #     print(noms)
            #     return numbers

            # parser = etree.XMLParser(root, remove_comments=True)
            # d = defaultdict(list)
            # for sample in parser.xpath('//race/nomination'):
            #     print(sample)
            # for sample in root.xpath('//race/nomination'):
            #     # print(sample)
            #     dct = sample.attrib
            #     for k in atts:
            #         # print(k)
            #         d[k].append(dct[k])

            # print(d["number"])
            return noms


a = parseXML()
for sample in a.items:
    print(sample["number"])

Confused

Sayth

[toc] | [next] | [standalone]


#110494

Fromdieter <dieter@handshake.de>
Date2016-06-25 09:50 +0200
Message-ID<mailman.110.1466841055.11516.python-list@python.org>
In reply to#110475
Sayth Renshaw <flebber.crue@gmail.com> writes:
> ...
> Can I ask is there something obvious wrong, i have left the commented other versions in they "work" in that they all produce the same output the print whole file.
>

The code below is obviously wrong - it is surprising that you get
anything other than an exception. See comments below inserted into
your code.

> def parseXML():
> ...
>             result = etree.tostring(tree.getroot(), pretty_print=True)

"result" here is obviously a string.

>             for sample in result:

This means that "sample" successively hold the characters composing
the string "result".

>                 noms = (dict(zip(atts, map(sample.attrib.get, atts))))

You should get "AttributeError: str object does not have attribute `attrib`".

[toc] | [prev] | [next] | [standalone]


#110497

FromSayth Renshaw <flebber.crue@gmail.com>
Date2016-06-25 01:41 -0700
Message-ID<fcacd6e0-b0d7-45e4-830a-3de93aab4299@googlegroups.com>
In reply to#110494
> 
> The code below is obviously wrong - it is surprising that you get
> anything other than an exception. See comments below inserted into
> your code.
> 
> > def parseXML():
> > ...
> >             result = etree.tostring(tree.getroot(), pretty_print=True)
> 
> "result" here is obviously a string.
> 
> >             for sample in result:
> 
> This means that "sample" successively hold the characters composing
> the string "result".
> 
> >                 noms = (dict(zip(atts, map(sample.attrib.get, atts))))
> 
> You should get "AttributeError: str object does not have attribute `attrib`".

The attrib is an lxml function, when you have defined a root 
http://lxml.de/tutorial.html
>>> attributes = root.attrib
or
>>> d = dict(root.attrib)
>>> sorted(d.items())
[('hello', 'Guten Tag'), ('interesting', 'totally')]

if I run it with this section as you reference above

for sample in root.xpath('//race/nomination'):
                noms = (dict(zip(atts, map(sample.attrib.get, atts))))
                print(noms)

I get working output

(pyxml) [sayth@localhost pyXML]$ python xrace.py data/ -e .xml
{'barrier': '5', 'horse': 'Chipanda', 'goodtrack': '0-0-0-0', 'weight': '54', 'pricestarting': '$3.50', 'age': '3', 'description': 'B F 2 Sepoy x Lobola (Anabaa(USA))', 'heavytrack': '0-0-0-0', 'career': '2-0-0-2 $30225.00', 'colours': 'Royal Blue', 'finished': '1', 'owners': 'Godolphin ', 'dob': '2013-10-08T00:00:00', 'id': '198926', 'thisdistance': '0-0-0-0', 'weightvariation': '0', 'penalty': '0', 'number': '8', 'rating': '0', 'sex': 'F', 'decimalmargin': '0.00', 'variedweight': '54', 'saddlecloth': '8', 'thistrack': '1-0-0-1 $15000.00'}
{'barrier': '1', 'horse': 'Legerity', 'goodtrack': '3-1-0-1 $77150.00', 'weight': '57.5', 'pricestarting': '$2.50F', 'age': '3', 'description': 'B C 2 Snitzel x

Cheers

Sayth

[toc] | [prev] | [next] | [standalone]


#110565

Fromdieter <dieter@handshake.de>
Date2016-06-27 09:08 +0200
Message-ID<mailman.21.1467011309.2358.python-list@python.org>
In reply to#110497
Sayth Renshaw <flebber.crue@gmail.com> writes:
>> The code below is obviously wrong - it is surprising that you get
>> anything other than an exception. See comments below inserted into
>> your code.
>> 
>> > def parseXML():
>> > ...
>> >             result = etree.tostring(tree.getroot(), pretty_print=True)
>> 
>> "result" here is obviously a string.
>> 
>> >             for sample in result:
>> 
>> This means that "sample" successively hold the characters composing
>> the string "result".
>> 
>> >                 noms = (dict(zip(atts, map(sample.attrib.get, atts))))
>> 
>> You should get "AttributeError: str object does not have attribute `attrib`".
>
> The attrib is an lxml function, when you have defined a root 
> http://lxml.de/tutorial.html

Correctly, this should read: "attrib" is an attribute of "ETree" nodes (!)
(providing a mapping like access to the nodes attributes).

It is *NOT* an attribute of string (!) objects.

You have converted the tree root into a string (using "etree.tostring")
and then iterated over the resulting string. On those characters
you access "attrib" - which will not work as you expect.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web