簡體   English   中英

如何使用枚舉鍵將用戶輸入添加到字典中?

[英]How to add user input into a dictionary with enumerated keys?

我一直在研究一個關於操縱字典以及如何閱讀它們的實驗室。 我遇到了一個問題,讓我們要求用戶輸入,將其添加到字典中。

我被卡住的原因是因為我列舉了鍵的輸入,我不知道如何在不擔心鍵的情況下向字典中添加更多內容。 我是否需要退后一步並重新設計密鑰的創建方式?

dInput = input('Please enter a string ')
D = dict(enumerate(dInput))
print(D)
## This is where I enumerate the user input

plusDict = input('Enter another character to add to the dictionary ')
## User puts in a character and the script adds it to the dictionary with it's proper key.

在一個例子中:

Please enter a string: fff
{0: 'f', 1: 'f', 2: 'f'}

Enter another character to add to the dictionary: e

期望的結果

{0: 'f', 1: 'f', 2: 'f', 3: 'e'}

我已經刪除了大部分允許用戶通過輸入訪問字典的腳本,因為這是我唯一被困住的地方。謝謝你的時間!

Enumerate接受一個可選的第二個參數,告訴它從哪里開始。 您可以跟蹤此並在枚舉時使用它以使值不斷增加。 (當然你知道列表會更好)。

D = {}
index = 0

dInput = input('Please enter a string ')
# input abc
D.update(enumerate(dInput, index))
index += len(dInput)
print(D)
# prints 
# {0: 'a', 1: 'b', 2: 'c'}


dInput = input('Please enter a string ')
# input def
D.update(enumerate(dInput, index))
index += len(dInput)
print(D)
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

沒有必要重寫代碼。 如果您要做的只是添加一個新字符,其鍵是下一個可用的整數,只需執行以下操作:

D[len(D)] = plusDict

如果要一次添加多個字符,可以執行以下操作:

for char in plusDict: D[len(D)] = char

暫無
暫無

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

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