Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - Create a list of sublist while itiretating through XML file

my problem is the following: I cannot figure out how to create a dictionary of different variable from an xml file using lxml library.

Here's an example of the xml file :

  <Patterns>
    <Pattern ID="0" weight="1">
      <PatternEntries>
        <PatternEntry index="0">
          <ShiftType>L</ShiftType>
        </PatternEntry>
        <PatternEntry index="1">
          <ShiftType>D</ShiftType>
        </PatternEntry>
      </PatternEntries>
    </Pattern>
    <Pattern ID="1" weight="1">
      <PatternEntries>
        <PatternEntry index="0">
          <ShiftType>D</ShiftType>
        </PatternEntry>
        <PatternEntry index="1">
          <ShiftType>E</ShiftType>
        </PatternEntry>
      </PatternEntries>
    </Pattern>

What I would like is to create a dictionary with the pattern ID as key and the shift type and day as value who would look like this: {Pattern ID :[ShiftType]}. The problem comes from the list of shift. So what I was thinking its creating a sublist where each element of each ID are store in a sublist and all the element of all ID are stored into one generic list. Thank you ! Here's my code

for ID in root.xpath('//Patterns'):
    pattern_ID = ID.xpath('./Pattern/@ID')
    for shift in root.xpath('.//PatternEntries/PatternEntry/ShiftType'):
        shift_list.append(shift.text)

Expected output:

{0:[L,D], 1:[D,E]}

question from:https://stackoverflow.com/questions/65924243/create-a-list-of-sublist-while-itiretating-through-xml-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably need something along these lines:

from lxml import etree
patterns = """[your xml above, fixed - it's missing the closing </Patterns>]"""

doc = etree.fromstring(patterns)
p_dict = {}
pat = doc.xpath('//Pattern')
for p in pat:
    key = p.xpath('./@ID')[0]
    vals = p.xpath('.//ShiftType/text()')
    p_dict[key]=vals
p_dict

Output:

{'0': ['L', 'D'], '1': ['D', 'E']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...