【问题标题】:Array of dictionaries in PythonPython中的字典数组
【发布时间】:2020-09-17 05:24:43
【问题描述】:

我正在尝试创建一个 Python 字典数组,其中输入顺序很重要,并且数据可能具有各种类型。 (即字符串、整数、浮点数等)

这是 Lua 中的示例:

build =
{
    { 
        Type =                  SubSystem, 
        ThingToBuild =          "fighter",
        RequiredResearch =      "",
        RequiredShipSubSystems =    "",
        DisplayPriority =       0,
        DisplayedName =         "$7000",
        Description =           "$7001"
    },
    { 
        Type =                  SubSystem, 
        ThingToBuild =          "corvette",
        RequiredResearch =      "",
        RequiredShipSubSystems =    "",
        DisplayPriority =       0,
        DisplayedName =         "$7002",
        Description =           "$7003"
    },
    { 
        Type =                  SubSystem, 
        ThingToBuild =          "frigate",
        RequiredResearch =      "",
        RequiredShipSubSystems =    "",
        DisplayPriority =       0,
        DisplayedName =         "$7004",
        Description =           "$7005"
    },
}

如何在 Python 中使用类似的速记/语法糖来完成此任务?谢谢。

【问题讨论】:

  • Python会记住输入列表/字典项的顺序吗?
  • 你已经尝试过什么,你在哪里卡住了?
  • 我对 Python 不是很熟悉。 This site 表示使用 OrderedDict 但不使用速记。

标签: python arrays dictionary


【解决方案1】:

Python 的数组称为列表,您将它们放在方括号中。

字典在大括号中,但文字键必须用引号引起来,并且您使用: 来分隔键和值。

build = [
    { 
        "Type":                  SubSystem, 
        "ThingToBuild":          "fighter",
        "RequiredResearch":      "",
        "RequiredShipSubSystems":    "",
        "DisplayPriority":       0,
        "DisplayedName":         "$7000",
        "Description":           "$7001"
    },
    { 
        "Type":                  SubSystem, 
        "ThingToBuild":          "corvette",
        "RequiredResearch":      "",
        "RequiredShipSubSystems":    "",
        "DisplayPriority":       0,
        "DisplayedName":         "$7002",
        "Description":           "$7003"
    },
    { 
        "Type":                  SubSystem, 
        "ThingToBuild":          "frigate",
        "RequiredResearch":      "",
        "RequiredShipSubSystems":    "",
        "DisplayPriority":       0,
        "DisplayedName":         "$7004",
        "Description":           "$7005"
    }
]

从 Python 3.7 开始,字典会保留元素的顺序。在此之前,必须使用OrderedDict

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2015-10-17
    相关资源
    最近更新 更多