【问题标题】:Have a query on Dictionary Topic in Python在 Python 中查询字典主题
【发布时间】:2020-07-07 05:13:25
【问题描述】:

我无法继续使用 Python 练习的程序。这是关于 Python 中的字典。

问题是:编写一个python程序来检查给定的键是否存在,如果存在则打印值,否则添加一个新的键和值。

我的解决方案:

class Pro2:
    def check(self):
        dict = {}
        a=""
        b=""
        c=""
        d=""
        for x in range(5):
            a=(input("Enter key: "))
            b=(input("Enter value: "))
            dict[f"{a}":f"{b}"]
        c=input("Enter a key which is to be checked: ")
        if (dict.__contains__(c)):
            print(dict[c])
        else:
            d=input("Enter the value to be added: ")
            dict[f"{c}":f"{d}"]

现在出现的问题是,接受的输入没有附加到“for”循环中的相应字典中。 任何人都可以帮助我。更好的解决方案的建议也被接受。 提前谢谢你!

【问题讨论】:

    标签: python dictionary for-loop user-input


    【解决方案1】:

    您分配的 dict 值错误

    错误:

    dict[f"{c}":f"{d}"]
    

    所以dict[#add key here#] = #your value

    如果你在list([:]) 中执行:,它用于拆分列表,: 左右的值应该是索引(int) 或空(@987654329 @)

    更正:

    dict = {}
    a = "hello"
    b =  "world"
    dict[f"{a}"]=f"{b}"
    

    【讨论】:

    • 非常感谢。我实际上忘记了导致错误的那部分。谢谢!
    • @TheSarvesh 我很高兴能提供帮助!如果您的问题得到解决,请将其标记为答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2014-06-14
    相关资源
    最近更新 更多