在 Python 中查询字典主题

Have a query on Dictionary Topic in Python

我无法继续我在 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' 循环中的相应词典中。 谁能帮帮我。也接受更好解决方案的建议。 提前致谢!

您分配的 dict 值错误

错误:

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

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

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

更正:

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