Python plistlib:没有正确嵌套?

发布于 2024-12-06 00:59:37 字数 1149 浏览 0 评论 0原文

我的代码:

current_bex = dict(
    objectName = 'myData',
    objects = list(
        dict(
            one = 1,
            foo = 'bar',
        ),
    ), )

try:
        writePlist(current_bex, 'someFile.plist') except TypeError:
        print 'caught typeerror'

结果:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>objectName</key>
    <string>myData</string>
    <key>objects</key>
    <array>
        <string>foo</string>
        <string>one</string>
    </array>
</dict>
</plist>

我的问题是,为什么在嵌套数组中,我有简单的字符串,而不是foobar等?

编辑:

current_bex = dict(
    objectName = 'myData',
    objects = [
        {
            'one': 1,
            'foo': 'bar',
        },
        {
            'something': 'goes here',
        },
    ],
)

工作正常。显然我对 dict() 和 list() 的使用不正确?谁能阐明这一点?

My code:

current_bex = dict(
    objectName = 'myData',
    objects = list(
        dict(
            one = 1,
            foo = 'bar',
        ),
    ), )

try:
        writePlist(current_bex, 'someFile.plist') except TypeError:
        print 'caught typeerror'

results in:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>objectName</key>
    <string>myData</string>
    <key>objects</key>
    <array>
        <string>foo</string>
        <string>one</string>
    </array>
</dict>
</plist>

My question is, why, in the nested array, do I have simple strings, rather than <key>foo</key><string>bar</string>, etc?

EDIT:

current_bex = dict(
    objectName = 'myData',
    objects = [
        {
            'one': 1,
            'foo': 'bar',
        },
        {
            'something': 'goes here',
        },
    ],
)

works fine. Apparently my use of dict() and list() is incorrect? Can anyone shed light on this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧时模样 2024-12-13 00:59:37

这里有两件事:

  1. list() 构造函数不将单个内容项作为参数,它采用可迭代的项。因此,您可以编写列表文字语法[1, 2, 3],但不能编写list(1, 2, 3)

  2. 字典是可迭代的,并生成其键作为其值。

因此,如果您从字典构造一个列表,结果将是该字典的键列表,而不是包含字典的列表。这正是您在结果列表中看到的内容。

>>> list(dict(one=1, foo='bar'))
['foo', 'one']

Two things here:

  1. The list() constructor doesn't take individual content items as arguments, it takes an iterable of items. So you can write the list literal syntax[1, 2, 3], but not list(1, 2, 3).

  2. A dict is iterable, and yields its keys as its values.

So, if you construct a list from a dict, the result will be a list of the keys of the dict, not a list containing a dict. That's exactly what you're seeing in the resulting plist.

>>> list(dict(one=1, foo='bar'))
['foo', 'one']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文