Search code examples
pythondictionaryfor-loopuser-input

Have a query on Dictionary Topic in Python


I am not able to proceed in a program I was practicing in Python. It is about Dictionaries in Python.

The Question is : Write a python program to check whether the given key is present, if present print the value , else add a new key and value.

My solution:

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}"]

Now the problem occurring is that, the accepted input is not being appended in the respective Dictionary in the 'for' loop. Can anybody please help me. Suggestions for better solutions are also accepted. Thank You in Advance!


Solution

  • You are assigning the dict values wrong

    Error:

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

    so dict[#add key here#] = #your value

    also if you do : in a list([:]) it is used to split the list and values to left and right of : should be indexes(int) or empty ( )

    Correction:

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