[英]Adding a key, value to a dict, but I didn't tell it to?
我正在編寫 python 3.7 中的一些游戲代碼。 我使用很多字典來存儲各種數據,有一次我需要一個新字典來存儲一個字典中的某些值作為其他字典中的鍵。 當我運行代碼時,我最終在我的新字典中得到了一個值,但我無法弄清楚它為什么會出現在那里。 例子:
data = {'value1': 4, 'value2': 'hello'}
target = {'value1': 3}
def fillTarget(info, times):
for key, value in info.items():
if key == 'value2':
target[key] = value
target[value] = times
else:
for _ in range(times):
target[key] = target[key] + info[key]
fillTarget(data, 4)
當我打印(目標)時,我最終得到:
{'value1': 19, 'value2': 'hello', 'hello': 4}
為什么我將“value2”作為(目標)中的鍵值? 第 6-8 行不是告訴它將值作為鍵添加,但是 else: 不應該將鍵轉移到(目標)?
您正在向字典添加兩個項目
target[key] = value //{'value2': 'hello'}
// and
target[value] = times //{'hello': 4 }
//where key = 'value2', value = 'hello' and times = 4
單擊此處以獲取有關如何在 python 中將項目添加到字典的更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.