【问题标题】:Python plistlib: not nesting properly?Python plistlib:没有正确嵌套?
【发布时间】:2011-09-20 18:51:10
【问题描述】:

我的代码:

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() 的使用不正确?有人能解释一下吗?

【问题讨论】:

    标签: python list dictionary plist


    【解决方案1】:

    这里有两件事:

    1. list() 构造函数不将单个内容项作为参数,它需要一个可迭代的项。所以你可以写列表文字语法[1, 2, 3],但不能写list(1, 2, 3)

    2. 一个 dict 是可迭代的,并产生它的键作为它的值。

    所以,如果你从 dict 构造一个列表,结果将是 dict 的键列表,而不是包含 dict 的列表。这正是您在生成的 plist 中看到的内容。

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

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2015-12-31
      • 2018-03-18
      • 2021-12-01
      • 2019-07-25
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多