Python的初学者。在Python中检查一个键是否存在于一个字典中

173 阅读21分钟

我们使用 python 字典来存储键-值对。有时,我们需要检查一个键是否存在于字典中。在这个 Python 教程中,我们将通过工作实例讨论不同的方法来检查一个键是否存在于一个给定的 python 字典中。

目录

  1. 使用get()方法检查一个键是否存在于字典中
    1. get()方法
    2. 使用get()方法检查一个字典中是否有多个键存在
    3. 使用 get() 方法检查一个键是否存在于一个字典列表中
  2. 用for循环检查一个键是否存在于一个字典中
    1. 使用for循环检查一个字典中是否有多个键存在
    2. 使用for循环检查一个键是否存在于字典的列表中
  3. 使用成员操作符检查一个键是否存在于一个字典中
    1. 使用成员操作符检查是否有多个键存在于一个字典中
    2. 在Python中使用成员操作符检查一个键是否存在于字典的列表中。
  4. 使用keys()方法检查一个键是否存在于一个字典中
    1. keys()方法
    2. 使用keys()方法检查一个字典中是否有多个键存在
    3. 使用keys()方法检查一个键是否存在于字典的列表中。
  5. 使用viewkeys()方法检查一个键是否存在于字典中
    1. viewkeys()方法
    2. 使用viewkeys()方法检查一个字典中是否有多个键存在
    3. 使用viewkeys()方法检查一个键是否存在于字典的列表中
  6. 使用iterkeys()方法检查一个键是否存在于一个字典中
    1. iterkeys()方法
    2. 使用iterkeys()方法检查一个字典中是否有多个键存在
    3. 使用iterkeys()方法检查一个键是否存在于字典的列表中
  7. 结论

使用get()方法检查一个键是否存在于一个字典中

get()方法

get() 方法,当在一个python 字典上调用时,将一个键作为输入参数,并返回与该键在字典中的关联值。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
print("The input key is:", key)
value = myDict.get(key)
print("The associated value is:", value)

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: name
The associated value is: Python For Beginners

如果键在字典中不存在, get() 方法返回None ,如下所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
value = myDict.get(key)
print("The associated value is:", value)

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: Aditya
The associated value is: None

在这里,你可以看到键 'Aditya' 并不存在于字典中。因此,get() 方法返回值None

要使用 get() 方法检查一个给定的特定键是否存在于字典中,我们将在字典上调用get() 方法,并将键作为输入参数传递。如果get() 方法返回None ,我们就说这个键不存在于 dictionary 中。否则,我们就说这个键存在于 dictionary 中。你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
value = myDict.get(key)
if value is None:
    print("The key doesn't exist in the dictionary.")
else:
    print("The key exists in the dictionary.")

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: Aditya
The key doesn't exist in the dictionary.

上面的方法只有在字典中的键都没有与之相关的值None 时才有效。如果一个键有None 作为它的值,程序将给出错误的结果。例如,请看下面的源代码。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog","Aditya":None}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
value = myDict.get(key)
if value is None:
    print("The key doesn't exist in the dictionary.")
else:
    print("The key exists in the dictionary.")

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'Aditya': None}
The input key is: Aditya
The key doesn't exist in the dictionary.

在这里,你可以看到键 'Aditya' 存在于字典中。但是,程序给出一个错误的结果,说这个键不在字典中。这是由于键 'Aditya' 在字典中的关联值为None

使用 get() 方法检查多个键是否存在于一个字典中

给定一个键的列表,如果我们需要检查多个键是否存在于一个字典中,我们将遍历这个键的列表。在迭代过程中,我们将在字典上调用 get() 方法,以当前的键作为其输入参数。

在 for 循环中,如果get() 方法返回None ,我们将说这个键不存在于 dictionary 中。否则,我们将说这个键存在于字典中。

你可以在下面的例子中观察这个过程。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = ["Aditya","name","url"]
print("The input keys are:", keys)
for key in keys:
    value = myDict.get(key)
    if value is None:
        print("The key '{}' doesn't exist in the dictionary.".format(key))
    else:
        print("The key '{}' exists in the dictionary.".format(key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' exists in the dictionary.
The key 'url' exists in the dictionary.

使用 get() 方法检查一个键是否存在于一个字典列表中

为了检查一个键是否存在于字典列表中,我们将使用for循环来迭代字典列表。在迭代过程中,我们将在每个字典上调用get() 方法,并将 key 作为其输入参数。

如果任何一个字典返回的值不是None ,我们将说这个键存在于字典列表中。一旦我们找到了这个键,我们将使用break语句走出这个循环。

如果get() 方法对一个字典返回None ,我们将使用 continue 语句移到下一个字典。

如果get() 方法对所有的字典都返回 None,我们将说这个键不存在于字典的列表中。你可以在下面的例子中观察到这一点。

listOfDicts = [{1: 1, 2: 4, 3: 9},
               {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
                "type": "python blog"},
               {"person": "Aditya", "Country": "India"}
               ]
key = "Aditya"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
    value = dictionary.get(key)
    if value is not None:
        print("The key '{}' is present in the list of dictionaries.".format(key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' is not present in the list of dictionaries.".format(key))

输出。

The key is: Aditya
The key 'Aditya' is not present in the list of dictionaries.

使用for循环检查一个键是否存在于一个字典中

使用get() 方法有很高的时间复杂性,因为我们需要检索与每个键相关的值。我们可以通过直接检查一个键在字典中是否存在来避免这种情况,如下图所示,使用for循环。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "url"
print("The input key is:", key)
keyFound = False
for keys in myDict:
    if keys == key:
        print("The key '{}' is present in the dictionary.".format(key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' is not present in the dictionary.".format(key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: url
The key 'url' is present in the dictionary.

在这里,字典作为一个包含键的容器对象工作。我们通过迭代器逐一检查所需的键是否存在于 dictionary 中。

使用 for 循环检查多个键是否存在于一个字典中

为了检查多个键是否存在于字典中,我们将在键的列表上进行迭代。在迭代输入键的同时,我们将迭代字典,检查每个输入键是否存在于字典中。

如果在 dictionary 中找到一个键,我们就说这个键存在于 dictionary 中。否则就不是。

一旦在 dictionary 中找到一个键,我们将使用 break 语句从内部 for 循环中出来。

在检查了一个键是否存在于 dictionary 中之后,我们将移到下一个键,并重复同样的过程。你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for key in input_keys:
    keyFound = False
    for keys in myDict:
        if keys == key:
            print("The key '{}' is present in the dictionary.".format(key))
            keyFound = True
            break
        else:
            continue
    if not keyFound:
        print("The key '{}' is not present in the dictionary.".format(key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' is not present in the dictionary.
The key 'name' is present in the dictionary.
The key 'url' is present in the dictionary.

使用for循环检查一个键是否存在于一个字典列表中

为了检查一个键是否存在于字典列表中,我们将首先使用for循环遍历字典列表中的每个字典。在迭代的同时,我们将使用另一个for循环来检查输入的键是否存在于字典中。一旦我们发现键存在于一个字典中,我们将打印该键存在于字典的列表中。之后,我们将使用 break 语句移出 for 循环。

如果字典列表中没有一个字典有输入的键,我们将打印出该键不存在于字典中。你可以在下面的例子中观察到这一点。

listOfDicts = [{1: 1, 2: 4, 3: 9},
               {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
                "type": "python blog"},
               {"person": "Aditya", "Country": "India"}
               ]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
    for keys in dictionary:
        if keys == key:
            print("The key '{}' is present in the list of dictionaries.".format(key))
            keyFound = True
            break
        else:
            continue
if not keyFound:
    print("The key '{}' is not present in the list of dictionaries.".format(key))

输出。

The key is: name
The key 'name' is present in the list of dictionaries.

使用成员运算符检查一个键是否存在于字典中

成员操作符(in operator) 用于检查一个元素是否存在于容器对象中。

要检查一个键在字典中是否存在,我们可以使用 in 操作符,如下图所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
if key in myDict:
    print("The key '{}' is present in the dictionary.".format(key))
else:
    print("The key '{}' is not present in the dictionary.".format(key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: Aditya
The key 'Aditya' is not present in the dictionary.

使用成员操作符检查多个键是否存在于字典中

为了检查字典中是否有多个键,我们将使用for循环和成员操作符。我们将使用for循环遍历键的列表。在迭代过程中,我们将使用成员运算符检查一个键是否存在于字典中。如果我们发现一个键存在于 dictionary 中,我们将说这个键存在于 dictionary 中。否则就不存在。

你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for key in input_keys:
    if key in myDict:
        print("The key '{}' is present in the dictionary.".format(key))
    else:
        print("The key '{}' is not present in the dictionary.".format(key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' is not present in the dictionary.
The key 'name' is present in the dictionary.
The key 'url' is present in the dictionary.

使用成员运算符检查一个键是否存在于 Python 的字典列表中

给定一个字典列表,如果我们需要检查一个键是否存在于一个字典中,我们将使用以下过程。

我们将使用一个 for 循环遍历字典列表。在迭代过程中,我们将使用成员操作符检查键是否存在于每个字典中。如果我们在当前的字典中没有找到这个键,我们将移到下一个字典。一旦我们发现这个键存在于字典中,我们将打印这个键存在于字典中。之后,我们将使用 break 语句退出这个循环。

如果我们在任何一个字典中都没有找到这个键,我们将在最后打印这个键。你可以在下面的例子中观察到这一点。

listOfDicts = [{1: 1, 2: 4, 3: 9},
               {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
                "type": "python blog"},
               {"person": "Aditya", "Country": "India"}
               ]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
    if key in dictionary:
        print("The key '{}' is present in the list of dictionaries.".format(key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' is not present in the list of dictionaries.".format(key))

输出。

The key is: name
The key 'name' is present in the list of dictionaries.

使用keys()方法检查一个键是否存在于一个字典中

keys()方法

keys() 方法,当对一个字典调用时,会返回一个dict_keys 对象的副本,其中包含字典中存在的所有键,如下面的python脚本所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys=myDict.keys()
print("The keys are:", keys)

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])

要使用keys() 方法检查一个特定的键是否存在于一个 dictionary 中,我们首先要获得dict_keys 对象。之后,我们将使用for循环遍历dict_keys 对象。在迭代过程中,我们将检查当前的键是否是我们要搜索的键。如果是,我们将说这个键存在于字典中。否则就不是。你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys are:", keys)
input_key = "url"
keyFound = False
for key in keys:
    if key == input_key:
        print("The key '{}' exists in the dictionary.".format(input_key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' does not exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
The key 'url' exists in the dictionary.

不使用 for 循环,我们也可以使用成员运算符来检查这个键是否存在于字典中,如下图所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys are:", keys)
input_key = "url"
if input_key in keys:
    print("The key '{}' exists in the dictionary.".format(input_key))
else:
    print("The key '{}' doesn't exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
The key 'url' exists in the dictionary.

使用keys()方法检查多个键是否存在于一个字典中

为了检查多个键是否存在于字典中,我们将在输入键的列表上进行迭代。对于每个键,我们将使用成员操作符来检查这个键是否存在于keys() 方法返回的dict_key 对象中。如果是,我们将打印出这个键存在于字典中。否则,我们将打印出这个键不存在。最后,我们将移到下一个键。 你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys are:", keys)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for input_key in input_keys:
    if input_key in keys:
        print("The key '{}' exists in the dictionary.".format(input_key))
    else:
        print("The key '{}' doesn't exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' exists in the dictionary.
The key 'url' exists in the dictionary.

使用 keys() 方法检查一个键是否存在于字典列表中

要使用keys() 方法检查一个键是否存在于字典列表中,我们将使用以下程序。

  • 我们将使用 for 循环遍历字典的列表。
  • 在迭代一个字典时,我们将首先使用keys() 方法获得一个字典的键的列表。之后,我们将使用成员操作符来检查输入的键是否在键的列表中。
  • 如果该键存在于列表中,我们将打印出来。之后,我们将使用break语句退出for循环。
  • 如果我们在当前的键列表中没有找到这个键,我们将使用 continue 语句移到字典列表中的下一个字典。
  • 在遍历了所有的字典之后,如果我们没有找到这个键,我们将打印出这个键在字典中不存在。

你可以在下面的例子中观察整个过程。

listOfDicts = [{1: 1, 2: 4, 3: 9},
               {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
                "type": "python blog"},
               {"person": "Aditya", "Country": "India"}
               ]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
    keys = dictionary.keys()
    if key in keys:
        print("The key '{}' is present in the list of dictionaries.".format(key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' is not present in the list of dictionaries.".format(key))

输出。

The key is: name
The key 'name' is present in the list of dictionaries.

使用 viewkeys() 方法检查一个键是否存在于字典中

在 python 2.x 版本中,我们可以使用viewkeys() 方法而不是 keys 方法来检查一个键是否存在于字典中。

viewkeys() 方法

viewkeys() 方法,当对一个 python 字典调用时,返回一个包含字典中的键的dict_key 对象的视图,如下所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys=myDict.viewkeys()
print("The keys are:", keys)

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))

为了使用viewkeys() 方法检查一个指定的键是否存在于字典中,我们将首先使用viewkeys() 方法获得dict_keys 对象。之后,我们将使用for循环遍历dict_keys 对象。

在迭代过程中,我们将检查当前的键是否是我们要搜索的键。如果是,我们将说这个键存在于字典中。否则就不是。你可以在下面的代码中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.viewkeys()
print("The keys are:", keys)
input_key = "url"
keyFound = False
for key in keys:
    if key == input_key:
        print("The key '{}' exists in the dictionary.".format(input_key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' does not exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
The key 'url' exists in the dictionary.

我们可以不使用 for 循环,而是使用成员运算符来检查这个键是否存在于字典中,如下图所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.viewkeys()
print("The keys are:", keys)
input_key = "url"
if input_key in keys:
    print("The key '{}' exists in the dictionary.".format(input_key))
else:
    print("The key '{}' doesn't exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
The key 'url' exists in the dictionary.

使用viewkeys()方法检查多个键是否存在于一个字典中

要使用viewkeys() 方法检查一个字典中是否存在多个键,我们将遍历输入键的列表。

对于每个键,我们将使用成员操作符来检查这个键是否存在于由viewkeys() 方法返回的dict_keys 对象中。如果是,我们将打印出这个键存在于字典中。否则,我们将打印出这个键不存在。最后,我们将移到下一个键。 你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.viewkeys()
print("The keys are:", keys)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for input_key in input_keys:
    if input_key in keys:
        print("The key '{}' exists in the dictionary.".format(input_key))
    else:
        print("The key '{}' doesn't exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
('The input keys are:', ['Aditya', 'name', 'url'])
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' exists in the dictionary.
The key 'url' exists in the dictionary.

使用 viewkeys() 方法检查一个键是否存在于字典列表中

要使用viewkeys() 方法检查一个键是否存在于字典列表中,我们将使用以下程序。

  • 我们将使用 for 循环遍历字典的列表。
  • 在迭代一个字典时,我们将首先通过调用字典上的viewkeys() 方法获得dict_keys 对象。之后,我们将使用成员操作符来检查输入的键是否存在于dict_keys 对象中。
  • 如果该键存在于dict_keys 对象中,我们将打印出来。在这之后,我们将使用break语句离开for循环。
  • 如果我们在当前的dict_keys 对象中没有找到该键,我们将使用 continue 语句移到字典列表中的下一个字典。
  • 在遍历了所有的字典之后,如果我们没有找到键,我们将打印出该键在字典列表中不存在。

你可以在下面的例子中观察整个过程。

listOfDicts = [{1: 1, 2: 4, 3: 9},
               {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
                "type": "python blog"},
               {"person": "Aditya", "Country": "India"}
               ]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
    keys = dictionary.viewkeys()
    if key in keys:
        print("The key '{}' is present in the list of dictionaries.".format(key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' is not present in the list of dictionaries.".format(key))

输出。

('The key is:', 'name')
The key 'name' is present in the list of dictionaries.

使用iterkeys()方法检查一个键是否存在于一个字典中

在 python 2.x 版本中,我们也可以使用iterkeys() 方法而不是 viewkeys() 方法来检查一个键是否存在于一个字典中。

iterkeys() 方法

iterkeys() 方法,当对一个 python 字典调用时,返回一个迭代器,迭代字典中的键。

要使用iterkeys() 方法检查一个键是否存在于一个 dictionary 中,我们首先在 dictionary 上调用 iterkeys() 方法来获得迭代器。之后,我们将使用 for 循环和迭代器来迭代这些键。

在迭代过程中,我们将检查当前的键是否是我们要搜索的键。如果是,我们就说这个键存在于 dictionary 中。否则就不是。你可以在下面的 python 程序中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
iterator = myDict.iterkeys()
input_key = "url"
keyFound = False
for key in iterator:
    if key == input_key:
        print("The key '{}' exists in the dictionary.".format(input_key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' does not exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The key 'url' exists in the dictionary.

你可以使用成员运算符和 iterkeys() 方法来检查一个键是否存在于字典中,而不是使用 for 循环,如下所示。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
iterator = myDict.iterkeys()
input_key = "url"
if input_key in iterator:
    print("The key '{}' exists in the dictionary.".format(input_key))
else:
    print("The key '{}' doesn't exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The key 'url' exists in the dictionary.

使用iterkeys()方法检查一个字典中是否有多个键存在

要使用iterkeys() 方法检查一个字典中是否存在多个键,我们首先要使用iterkeys() 方法获得字典中键的迭代器。之后,我们将遍历输入键的列表。

对于每个键,我们将使用成员操作符来检查键是否存在于iterkeys() 方法返回的迭代器对象中。如果是,我们将打印出这个键存在于字典中。否则,我们将打印出这个键不存在。最后,我们将移动到下一个键。 你可以在下面的例子中观察到这一点。

myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
iterator = myDict.iterkeys()
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for input_key in input_keys:
    if input_key in iterator:
        print("The key '{}' exists in the dictionary.".format(input_key))
    else:
        print("The key '{}' doesn't exist in the dictionary.".format(input_key))

输出。

The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The input keys are:', ['Aditya', 'name', 'url'])
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' doesn't exist in the dictionary.
The key 'url' doesn't exist in the dictionary.

使用 iterkeys() 方法检查一个键是否存在于字典列表中

为了使用iterkeys() 方法检查一个键是否存在于字典列表中,我们将使用以下程序。

  • 我们将使用 for 循环来迭代字典列表。
  • 在迭代一个字典时,我们将首先通过在字典上调用iterkeys() 方法来获得字典的键的迭代器。然后,我们将使用成员操作符来检查输入的键是否存在于迭代器中。
  • 如果该键存在于迭代器中,我们将打印出来。之后,我们将使用break语句走出for循环。
  • 如果我们在当前的迭代器中没有找到键,我们将使用 python 的 continue 语句移动到字典列表的下一个字典。
  • 在遍历了所有的字典之后,如果我们没有找到这个键,我们将打印出这个键不存在于字典中。

你可以在下面的例子中观察整个过程。

listOfDicts = [{1: 1, 2: 4, 3: 9},
               {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
                "type": "python blog"},
               {"person": "Aditya", "Country": "India"}
               ]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
    iterator = dictionary.iterkeys()
    if key in iterator:
        print("The key '{}' is present in the list of dictionaries.".format(key))
        keyFound = True
        break
    else:
        continue
if not keyFound:
    print("The key '{}' is not present in the list of dictionaries.".format(key))

输出。

('The key is:', 'name')
The key 'name' is present in the list of dictionaries.

结论

在这篇文章中,我们讨论了检查一个键是否存在于python 字典中的不同方法。如果你使用的是 python 3.x,在所有的方法中,你应该使用成员运算符的方法来检查一个键是否存在于字典中。如果你在 python 2.x 中工作,你可以使用iterkeys() 的方法来检查一个给定的键是否存在于字典中。这两种方法对于各自版本的 python 是最快的。

我希望你喜欢阅读这篇文章。要了解更多关于python编程的信息,你可以阅读这篇文章:如何在Python中删除列表中出现的所有字符。你可能也喜欢这篇文章:如何检查一个Python字符串是否包含一个数字

请继续关注更多内容丰富的文章。

学习愉快!

The postCheck if a Key Exists in a Dictionary in Pythonappeared first onPythonForBeginners.com.