如何使用枚举键将用户输入添加到字典中?
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'}
我删除了大部分允许用户通过输入访问字典的脚本,因为这是我唯一被卡住的地方。谢谢你的时间!!
无需重写代码。如果您只想添加一个新字符,其键是下一个可用整数,只需执行:
D[len(D)] = plusDict
如果你想一次添加多个字符,你可以这样做:
for char in plusDict: D[len(D)] = char
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'}
我一直在做一个关于操作字典和如何阅读它们的实验室。我遇到了一个问题,该问题使我们要求用户输入并将其添加到字典中。
我卡住的原因是因为我已经枚举了键的输入,我不知道如何在不担心键的情况下向字典添加更多内容。我是否需要后退几步,重新研究密钥的创建方式?
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'}
我删除了大部分允许用户通过输入访问字典的脚本,因为这是我唯一被卡住的地方。谢谢你的时间!!
无需重写代码。如果您只想添加一个新字符,其键是下一个可用整数,只需执行:
D[len(D)] = plusDict
如果你想一次添加多个字符,你可以这样做:
for char in plusDict: D[len(D)] = char
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'}