【问题标题】:Verifying If key or value exists in dictionary, works for char and fails for number验证字典中是否存在键或值,适用于 char,适用于数字
【发布时间】:2013-05-20 08:23:19
【问题描述】:

为什么当我提供输入13 时,下面的程序什么也不返回。并且适用于c

#!/usr/local/bin/python3

d = {'a':1, 'b':3, 8:'c'}

x = input()
if x in d.values():
        print('In a dictionary')

更新: 如果我提供ab,则密钥也相同。有用。对于8,它不返回任何内容。

y = input()

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

我该怎么办?

【问题讨论】:

    标签: python dictionary python-3.x


    【解决方案1】:

    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'}
    

    【讨论】:

    • 谢谢,看起来很棒。但我仍然认为我应该将 dict 中的值/键转换为字符串,以便我可以直接使用它们。
    • 为此,您可以使用字典理解,请参阅更新后的答案。
    【解决方案2】:

    您正在使用 Python 3,其中 input() 返回 str。使用

    import ast
    x = ast.literal_eval(input())
    

    达到你想要的结果(假设你的输入是'c'(包括引号))

    例如。

    >>> import ast
    >>> d = {'a':1, 'b':3, 8:'c'}
    >>> ast.literal_eval(input()) in d.values()
    'c'
    True
    >>> ast.literal_eval(input()) in d.values()
    1
    True
    

    【讨论】:

    • 不错的一个。不知道这件事。谢谢。
    • @Drt 这是假设您使用的是 Python 文字,例如。 'c',你不能只输入c,因为这并不能神奇地检查它认为你拥有的变量类型
    • @jamylak 是的,我正在使用'c'
    • @Drt 是的,就像我说的那样,您使用了c 而不是'c'。看我的控制台输入我用'c',相当于ast.literal_eval("'c'")
    • 对于“'c'”它没有输出。如果我想使用c。我该怎么做
    【解决方案3】:

    首先,input() 返回一个字符串,在您的情况下,最好将值转换为字符串以便比较它们,因为您有混合值类型(不推荐)

    x = input()
    

    其次,检查 'x' 是否在 'd.values()' 中可能看起来很快,因为 'd.values()' 是一个迭代器,但使用 'in' 会将其视为一个列表.这样做会更快:

    for v in d.values():
        if x == str(v): # convert v to str
            print('In a dictionary')
            break
    else:
        print('NOT In a dictionary')
    

    这使用“for / else”规则,这意味着如果 for 循环完成了对 'd.values()' 中所有元素的迭代而没有 'break' 它将触发 'else'

    【讨论】:

    • 简单来说,key/value 是否存在,这看起来太麻烦了。没有其他简单的方法吗?
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2015-12-24
    • 2021-11-18
    • 2021-06-20
    • 2019-10-10
    • 2021-01-02
    相关资源
    最近更新 更多