【问题标题】:How to add user input into a dictionary with enumerated keys?如何使用枚举键将用户输入添加到字典中?
【发布时间】:2019-11-30 14:31:43
【问题描述】:

我一直在研究如何处理字典以及如何阅读它们的实验室。我遇到了一个问题,它让我们要求用户输入将其添加到字典中。

我被卡住的原因是因为我已经枚举了键的输入,我不知道如何在不担心键的情况下向字典中添加更多内容。我是否必须退后一步,重新设计密钥的创建方式?

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'}

我已经删除了大部分允许用户通过输入访问字典的脚本,因为这是我唯一遇到的问题。感谢您的宝贵时间!!

【问题讨论】:

  • 你想update 字典吗?
  • 如果这正是您想要的行为,您可以使用d[len(d)] = plusDict,但我想知道它与列表的不同之处。

标签: python python-3.x dictionary input enumeration


【解决方案1】:

无需重写代码。如果您只想添加一个新字符,其键是下一个可用整数,只需执行以下操作:

D[len(D)] = plusDict

如果你想一次添加多个字符,你可以这样做:

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

【讨论】:

  • 如果plusDict 不止一个字符怎么办?
  • @Tomerikoo OP 字面意思是“另一个角色”。如果超过一个,则用户没有按照指示进行操作。但是,当然,我明白你的意思。更新了我的答案。
  • 伙计,我知道事情就是这么简单。我在脚本中写了 D[x] = plusDict,知道它与此类似。欣赏!
  • @FernandoFlores 没问题。如果您的问题得到解决,请随时标记正确答案。
【解决方案2】:

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'}

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 2016-07-06
    • 2020-06-27
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多