Home > OS >  I want to compare this value of this variable to the dictionary and access its value and use it
I want to compare this value of this variable to the dictionary and access its value and use it

Time:09-17

cloth = {'shirt':1000,
        'jacket':2000,
        'cap':500}

for key,values in cloth.items():
    piece = input('tell item: ')
    if piece in cloth.keys():
        n = int(input('n: '))
        if n<=2:
            print(n*cloth.values())
            break
        else:
            print('out of range')
    else:
        print(None)

If I try to take input as 'cap' in piece input and 'n' as 2 as try to compare it to the value in dict, I want the final answer to be 1000 and instead I am getting the value to be capcap.

CodePudding user response:

You are using cloth.values() which is wrong, you need to use cloth[piece] for getting its value for a special key(in a dictionary).

 cloth = {'shirt':1000,
            'jacket':2000,
            'cap':500}
    
    for key,values in cloth.items():
        piece = input('tell item: ')
        if piece in cloth.keys():
            n = int(input('n: '))
            if n<=2:
                # look here
                print(n*cloth[piece])
                break
            else:
                print('out of range')
        else:
            print(None)
    
            

CodePudding user response:

The error is in the print(n*cloth.values()) line, since .values() returns a list of the values in the dictionary, and you can'T multiply an integer with that. Just use normal dictionary indexing to access the values of the dictionary: print(n * cloth[piece])

  • Related