簡體   English   中英

如何在另一個字典中創建字典?

[英]How do I create a dictionary within another dictionary?

現在我正在制作一個 python 程序,該程序采用名稱和統計數據並記錄它們。 為此,我試圖創建一個類似於此示例的嵌套字典。

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

當我嘗試做到這一點時,我的問題就出現了。 我的程序結構首先創建一個名稱列表,然后是一個統計類別列表,我正在嘗試在字典中創建一個字典來創建它。 我有一個名為 collectPlayerAttributes 的 function ,它創建了一個統計類別列表,一個例子是

 ["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

如果您只想創建一個所有玩家都有一個條目的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM