-2

I want to print('Doesn't exist') when the input is not a key in dictionary, it looks like its checking every single key in dictionary and prints if its there or not. I would like to ask if its possible to get output only one time if dictionary doesn't' contain input.

number = input('Number: ')

data = {
        '1' : 'One',
         '2' : 'Two',
         '3' : 'Three',

        }

number = number.upper()
for a, value in data.items():
    if a == number:
        print(number, ":", value)
    else:
         print('Doesnt exist here')

Number: 1
1 : One
Doesnt exist here
Doesnt exist here
Edyta
  • 1
  • 1
  • You don't need a loop. `if number in data: print data[number]` – John Gordon Sep 12 '19 at 23:33
  • Your code doesn't do what you describe. It scans all the items IN the dictionary, therefore they are known to exist. You are checking against a number and for all the items that DO exist you print "don't exit here". The python dictionaries have a built-in functionality to check whether a key exists. You can use it as **pppery** has suggested. If you want to do the exercise of iterating over a collection you should stop on the fist found item and either keep a flag, or break the code flow (like return from a function) – Dr Phil Sep 12 '19 at 23:33

4 Answers4

0

Don't use the upper() function. Keys aren't chars.

ttppbb
  • 65
  • 8
0

So you do not need to use for loop. instead of for loop add this line:

print(number, ":", data[number]) if number in data else print("Doesn't exist")

also eliminate that upper method since it is ineffective.

Have fun!

0

There are multiple possible solutions to this problem:

use in keyword

number = input('Number: ')

data = {
        '1' : 'One',
         '2' : 'Two',
         '3' : 'Three',
}

if number in data:
    print("{}: {}".format(number, data[number]))
else:
    print('Doesnt exist here')

OR Doc

The python dictionaries throws KeyError if the key is not in

try:
    print("{}: {}".format(number, data[number]))
except KeyError as ex:
    print('Doesnt exist here')

OR Doc

print(data.get(number, "Does not exist here"))

Hope this helps, Happy learning.

0
data = {
        '1' : 'One',
         '2' : 'Two',
         '3' : 'Three',
}
number = input('Number: ')
str_number = str(number)
if str_number in data:
    print(str_number, ":", data[str_number])
else:
     print('Doesnt exist here')
Massifox
  • 4,369
  • 11
  • 31