我一直在研究如何操作字典以及如何阅读字典。我陷入了一个问题,使我们要求用户输入将其添加到字典中。
我卡住的原因是因为我已经列举了键的输入,而且我不知道如何在不担心键的情况下向字典添加更多内容。我是否需要退后一步,并重新研究如何创建密钥?
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句