本文介绍了验证字典中是否存在键或值,可用于char并不能用于数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我提供输入1
或3
时,为什么下面的程序什么都不返回.并且在c
的情况下有效. #!/usr/local/bin/python3
d = {'a':1, 'b':3, 8:'c'}
x = input()
if x in d.values():
print('In a dictionary')
更新:如果我提供a
或b
,则密钥也相同.有用.对于8
,它不返回任何值.
y = input()
if y in d:
print('key in dictionary')
我应该怎么做?
解决方案
input()
返回一个字符串.以下代码可能会有用.
d = {'a':1, 'b':3, 8:'c'}
x = input()
from string import digits
if x in digits:
x = int(x)
if x in d.values():
print('In a dictionary', x)
>>>
c
In a dictionary c
>>>
3
In a dictionary 3
类似地,要签入密钥,请执行以下操作:
d = {'a':1, 'b':3, 8:'c'}
x = input()
from string import digits
if x in digits:
x = int(x)
if x in d.values():
print('In a dictionary', x)
if x in d:
print ("In keys!")
输出测试:
>>>
1
In a dictionary 1
>>>
a
In keys!
要将键和值转换为字符串,可以使用字典理解.
>>> d = {'a':1, 'b':3, 8:'c'}
>>> d = {str(x): str(d[x]) for x in d}
>>> d
{'8': 'c', 'a': '1', 'b': '3'}
Why is below program returns nothing when I provide input 1
or 3
. And 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 a dictionary')
UPDATE:Same for key also if I provide a
or b
. It works. For 8
, it returns none.
y = input()
if y in d:
print('key in dictionary')
What should I do for these?
解决方案
The input()
returns a string. Following code might be useful.
d = {'a':1, 'b':3, 8:'c'}
x = input()
from string import digits
if x in digits:
x = int(x)
if x in d.values():
print('In a dictionary', x)
>>>
c
In a dictionary c
>>>
3
In a dictionary 3
Similarly, to check in keys, do:
d = {'a':1, 'b':3, 8:'c'}
x = input()
from string import digits
if x in digits:
x = int(x)
if x in d.values():
print('In a dictionary', x)
if x in d:
print ("In keys!")
Output Test:
>>>
1
In a dictionary 1
>>>
a
In keys!
To convert the keys and values to strings, you can use a dictionary comprehension.
>>> d = {'a':1, 'b':3, 8:'c'}
>>> d = {str(x): str(d[x]) for x in d}
>>> d
{'8': 'c', 'a': '1', 'b': '3'}
这篇关于验证字典中是否存在键或值,可用于char并不能用于数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!