【问题标题】:Python - New key into nested dictionaryPython - 嵌套字典的新键
【发布时间】:2016-12-09 11:27:25
【问题描述】:

这里是 Python 菜鸟。我正在尝试将播放器值列表(HP、xpos、ypos 等)存储在嵌套字典中,以便于访问。所以..

players = {'John': {'HP': 10, 'xpos': 50, 'ypos': 46}}
print players['John']['HP']

这行得通,但是如果以后有新玩家加入,我该如何添加/追加?我试过了:

players['Paul']['HP'] = 50

还有……

players{'Paul': {'HP': 50, 'xpos': 10, 'ypos': 99}}

还有……

players['Paul': {'HP': 50, 'xpos': 10, 'ypos': 99}]

所有这些都会产生各种错误。我该怎么做?

【问题讨论】:

    标签: python dictionary nested


    【解决方案1】:

    Paul 的数据本身就是一本字典。在这种情况下,您可以这样做:

    players['Paul'] = {'HP': 50, 'xpos': 10, 'ypos': 99}
    

    换句话说,您正在尝试将一个名为 Paul 的新玩家插入到主 players 字典中,这将成为一个新键。该键本身作为其值与另一个字典相关联。

    【讨论】:

      【解决方案2】:

      您需要确定要添加或更新的值的键。例如,

      players['John']["example"] = 5
      

      {"example":5} 添加到 John 中。 您可以使用 dict 的其他部分以及更多值来执行此操作。

      【讨论】:

      • 这并没有解决问题。这不是向 John 添加额外数据,而是将新玩家及其相关数据添加到主 players 字典中。
      • 我解释说你可以用字典的其他部分做到这一点:)
      【解决方案3】:
      # i prefer the keyword solution
      players['Paul']  = dict(HP = 000, xpos = 000, ypos= 000)
      players['Paul']['HP'] = 50
      print players['Paul']['HP']
      # 50
      
      # here done by zip:
      # basic example
      _keys = ['HP', 'xpos', 'ypos']
      _values = [50, 60, 70]
      players['Paul'] = dict(zip(_keys, _values))
      print players['Paul']['HP']
      # 50
      

      【讨论】:

        猜你喜欢
        • 2014-03-30
        • 2021-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-04
        • 2022-01-15
        • 2018-02-09
        • 2016-11-24
        相关资源
        最近更新 更多