[英]Python: Inserting into dictionary using FOR Loop
我已經在論壇中搜索過,無法理解是否可以使用以下結構將新條目插入到我的Python詞典中...而不將其轉換為列表。
for x in range(3):
pupils_dictionary = {}
new_key =input('Enter new key: ')
new_age = input('Enter new age: ')
pupils_dictionary[new_key] = new_age
print(pupils_dictionary)
輸出如下:
Enter new key: Tim
Enter new age: 45
Enter new key: Sue
Enter new age: 16
Enter new key: Mary
Enter new age: 15
{'Mary': '15'}
為什么只有Mary:15進來,而沒有其他人進來?
謝謝/
這是因為您執行了瞳孔數= {}
在循環中,在每個循環中,其值都將重置為{}
建議:
使用raw_input代替輸入
所以這段代碼應該工作:
pupils_dictionary = {}
for x in range(3):
new_key = raw_input('Enter new key: ')
new_age = raw_input('Enter new age: ')
pupils_dictionary[new_key] = new_age
print(pupils_dictionary)
您可以在每個循環中重新創建字典:
for x in range(3):
pupils_dictionary = {}
new_key =input('Enter new key: ')
...
而是在循環外創建一次:
pupils_dictionary = {}
for x in range(3):
new_key =input('Enter new key: ')
...
您在遍歷循環時將字典重新定義為空。 代碼應該是。
pupils_dictionary = {}
for x in range(3):
new_key =input('Enter new key: ')
new_age = input('Enter new age: ')
pupils_dictionary[new_key] = new_age
print(pupils_dictionary)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.