【问题标题】:How do I create a dictionary within another dictionary?如何在另一个字典中创建字典?
【发布时间】:2021-05-15 16:53:45
【问题描述】:

现在我正在制作一个 python 程序,它可以获取名称和统计数据并记录它们。为此,我尝试创建一个类似于此示例的嵌套字典。

playerData = {"Jack": {"strength": 10, "intelligence": 5}, "John": {"strength": 8, "intelligence": 10}}

当我尝试成功时,我的问题就出现了。我的程序结构首先创建一个名称列表,然后是一个统计类别列表,我试图在字典中创建一个字典来创建它。我有一个名为 collectPlayerAttributes 的函数,它创建一个统计类别列表,例如

["strength", "intelect", "charisma"]

。我要做的是从该列表中提取值并将它们作为键输入到字典 playerData 中。使用前面的示例列表,这看起来像

{"Jack": {"strength": 10, "intelect": 5, "charisma": 8}}

附加到键的值只是占位符,但最后我打算按照以下方式做一些事情

input("What is Jack's strength? ")

并将结果放在那里。到目前为止我的代码是

playerData = {}
y = 0
for i in players:
  playerData[str(players[y])] = {#What goes here?}
  y += 1

【问题讨论】:

  • 我们不知道您的“统计列表”是什么。请提供预期的minimal, reproducible example (MRE)。
  • 不接受站外链接和文字图片;我们需要您的问题是独立的,以符合本网站的目的。
  • 我有一个名为 collectPlayerAttributes 的函数,它创建一个统计类别列表,例如 ["strength", "intelect", "charisma"]。我要做的是从该列表中提取值并将它们作为键输入到字典 playerData 中。使用前面的示例列表,这看起来像 {"Jack": {"strength": 10, "intelect": 5, "charisma": 8}}
  • 好的,那么对于strength,示例值10来自哪里?

标签: python dictionary iteration


【解决方案1】:

如果您只想创建一个所有玩家都有一个条目的dict,您可以为每个玩家创建一个空的dict

playerData = {i:{} for i in players}

如果您随后向用户询问strength 值,您可以这样做:

def updatePlayerAttribute(playerData, name, attribute):
    value = input(f'What is the {attribute} of {name}?')
    playerData[name][attribute] = value

name = "Jack"
attribute = "strength"
updatePlayerAttribute(playerData, name, attribute)
print(playerData)

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2016-10-05
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多