【问题标题】:How to remove key from dictionary? (asking user which one) Python如何从字典中删除键? (询问用户是哪一个)Python
【发布时间】:2023-01-09 19:44:42
【问题描述】:

我想从字典中删除键,但是一个用户输入,我已经写了这段代码,但它给了我这个错误:对于我在 phoneNumbers.keys() 中: RuntimeError:字典在迭代期间改变了大小


phoneNumbers = {'John': '534-7887', 'Steven': '988-1187', "Max" : "765-2334", "Matt" : "987-1222"}
remove = input("Which key do you want to remove? ")
for i in phoneNumbers.keys():
    if i == remove:
        del phoneNumbers[remove]
print(phoneNumbers)

我知道这个是正确的,但为什么我不能在循环时删除它。

phoneNumbers = {'John': '534-7887', 'Steven': '988-1187', "Max" : "765-2334", "Matt" : "987-1222"}
remove = input("Which key do you want to remove? ")
del phoneNumbers[remove]
print(phoneNumbers)

【问题讨论】:

  • 您好,欢迎来到 dba.se!这是一个Python编程问题,与数据库无关。我建议关闭它 - 你可以在 StackOverflow 上询问。如果您有数据库问题,请随时回来!

标签: python data-dictionary


【解决方案1】:

正如错误消息所建议的那样,避免迭代和更改大小相同的对象,它可能会产生副作用。而是迭代一个浅拷贝

for i in phoneNumbers.copy():
    if i == remove:
        del phoneNumbers[remove]
print(phoneNumbers)

【讨论】:

    猜你喜欢
    • 2022-08-08
    • 1970-01-01
    • 2012-07-01
    • 2021-11-18
    • 2017-05-02
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多