Dominic K
Dominic K

Reputation: 7085

Finding if a plist contains a key with a specific string

Below I have a xml/plist file (you may recognize it as a .tmTheme):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>settings</key>
<array>
    <dict>
        <key>name</key>
        <string>Comment</string>
        <key>scope</key>
        <string>comment</string>
        <key>settings</key>
        <dict>
            <key>foreground</key>
            <string>#75715E</string>
        </dict>
    </dict>
    <dict>
        <key>name</key>
        <string>String</string>
        <key>scope</key>
        <string>string</string>
        <key>settings</key>
        <dict>
            <key>foreground</key>
            <string>#E6DB74</string>
        </dict>
    </dict>
</array>
</dict>
</plist>

I'm trying to find if each dictionary contains a string scope and if the scope has a specific string, say comment. Then I need to go to the inner dictionary and retrieve the key foreground. In this case, I would need to retrieve #75715E.

I've started by using a = plistlib.readPlist() then b = a["settings"]. Then I'm not sure how I should approach it, keeping in mind I need to find the root dictionary later on so I can get the other dictionary in it.

Upvotes: 1

Views: 1782

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375864

my_plist = plistlib.readPlist()
settings = my_plist["settings"]
for d in settings:
    if "scope" in d:
        if "comment" not in d["scope"]:
            print "A scope with no comment!"
    else:
        print "A dict with no scope!"

Upvotes: 1

Related Questions