簡體   English   中英

Python-嵌套字典中的新鍵

[英]Python - New key into nested dictionary

Python noob在這里。 我正在嘗試在嵌套詞典中存儲玩家值(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}]

所有這些都會帶來各種錯誤。 我該怎么做?

Paul的數據本身就是字典。 在這種情況下,您可以這樣操作:

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

換句話說,您正試圖在主players字典中插入一個名為Paul的新玩家,這將成為新的鍵。 該鍵本身與另一個字典相關聯,作為其值。

您需要確定要添加或更新的值的鍵。 例如,

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

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

# 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

暫無
暫無

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

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