Search code examples
pythonxmlplist

Python nested Plist reading and writing


I have a plist that has many child nodes to it. I cant seem to find a way to access deep into those nodes and only get that layer out. So below, I want to get the Tester number. I can call

plist['Title']['Set']['Notes']['Tester']

But that will give me all the tester keys along with the key 'Param' and string 'WUT'. I need to index through all of these (and there are a lot) and they vary from file to file.

<key>Title</key>
<dict>
  <key>Set</key>
  <dict>
    <key>Notes</key>
    <dict>
      <key>Tester</key>
      <array>
        <dict>
          <key>13</key>
          <dict>
            <key>Param</key>
            <array>
              <string>WUT</string>
            </array>
          </dict>
        </dict>
        <dict>
          <key>82</key>
          <dict>
            <key>Param</key>
            <array>
              <string>WUT</string>
            </array>
          </dict>
        </dict>
        <dict>
          <key>64</key>
          <dict>
            <key>Param</key>
            <array>
              <string>WUT</string>
            </array>
          </dict>
        </dict>

Ideally i would like to get the values [13, 82, 64] in an array.

As a side note i know i can do this through the xml.etree.ElementTree library and run

plist[0][11][3][1][2][1][x][0].text

and run through with a for loop, but for what i am currently doing the plist package is a lot easier to use.


Solution

  • You're pretty close. You can get those tester keys by using the dict.keys() method.

    tester_keys = list(plist['Title']['Set']['Notes']['Tester'].keys())
    

    dict.keys() returns a sequence containing the keys in your dictionary (in your case, numbers). This sequence is then converted to a list by using list().