python - Verifying If key or value exists in dictionary, works for char and fails for number -


why below program returns nothing when provide input 1 or 3. , works in case of c.

#!/usr/local/bin/python3  d = {'a':1, 'b':3, 8:'c'}  x = input() if x in d.values():         print('in dictionary') 

update: same key if provide a or b. works. 8, returns none.

y = input()  if y in d:         print('key in dictionary') 

what should these?

the input() returns string. following code might useful.

d = {'a':1, 'b':3, 8:'c'}  x = input() string import digits if x in digits:     x = int(x) if x in d.values():     print('in dictionary', x)   >>>  c in dictionary c  >>>  3 in dictionary 3 

similarly, check in keys, do:

d = {'a':1, 'b':3, 8:'c'}  x = input() string import digits if x in digits:     x = int(x) if x in d.values():     print('in dictionary', x)  if x in d:     print ("in keys!") 

output test:

>>>  1 in dictionary 1 >>>  in keys! 

to convert keys , values strings, can use dictionary comprehension.

>>> d = {'a':1, 'b':3, 8:'c'} >>> d = {str(x): str(d[x]) x in d} >>> d {'8': 'c', 'a': '1', 'b': '3'} 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -