Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22464

Python for Beginners: Check if a Key Exists in a Dictionary in Python

$
0
0

We use python dictionaries to store key-value pairs. Sometimes, we need to check if a key exists in the dictionary or not. In this python tutorial, we will discuss different ways with working examples to check if a key exists in a given dictionary in python.

Check if a Key Exists in a Dictionary Using the get() Method

The get() Method

The get() method, when invoked on a python dictionary, takes a key as an input argument and returns the value associated with the key in the dictionary. 

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)

Output:

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

If the key is not present in the dictionary, the get() method returns None as shown below.

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)

Output:

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

Here, you can see that the key ‘Aditya‘ is not present in the dictionary. Therefore, the get() method returns the value None.

To check if a given specific key exists in a dictionary using the get() method, we will invoke the get() method on the dictionary and pass the key as the input parameter. If the get() method returns None, we will say that the key does not exist in the dictionary. Otherwise, we will say that the key exists in the dictionary. You can observe this in the following example.

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.")

Output:

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.

The above method only works if none of the keys in the dictionary have the value None associated with them. If a key has None as its value, the program will give erroneous results. For instance, look at the following source code.

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.")

Output:

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.

Here, You can observe that the key ‘Aditya‘ is present in the dictionary. However, the program gives an erroneous result saying that the key is not present in the dictionary. This is due to the reason that the key ‘Aditya‘ has None as its associated value in the dictionary.

Check if Multiple Keys Exist in a Dictionary Using the get() Method

Given a list of keys, if we need to check if multiple keys exist in a dictionary or not, we will iterate over the list of keys. While iteration, we will invoke the get() method on the dictionary with the current key as its input argument.

In the for loop, if the get() method returns None, we will say that the key doesn’t exist in the dictionary. Otherwise, we will say that the key exists in the dictionary.

You can observe the process in the following example.

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))

Output:

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.

Check if a Key Exists in a List of Dictionaries Using the get() Method

To check if a key exists in a list of dictionaries, we will use a for loop to iterate over the list of dictionaries. While iteration, we will invoke the get() method on each dictionary with the key as its input argument.

If any of the dictionaries returns a value other than None, we will say that the key exists in the list of dictionaries. Once we find the key, we will come out of the loop using a break statement.

If the get() method returns None for a dictionary, we will move to the next dictionary using the continue statement.

If the get() method returns None for all the dictionaries, we will say that the key doesn’t exist in the list of dictionaries. You can observe this in the following example.

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))

Output:

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

Check if a Key Exists in a Dictionary Using the for Loop

Using the get() method has high time complexity as we need to retrieve the value associated with each key. We can avoid this by directly checking the existence of a key in a dictionary or not using a for loop as shown below.

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))

Output:

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.

Here, the dictionary works as a container object containing the keys. We iterate through the iterator and check one by one if the desired key exists in the dictionary.

Check if Multiple Keys Exist in a Dictionary Using a for Loop

To check if multiple keys exist in a dictionary, we will iterate over the list of keys. While iterating over input keys, we will iterate over the dictionary to check if each input key is present in the dictionary.

If a key is found in the dictionary, we will say that the key is present in the dictionary. Otherwise not.

Once a key is found in a dictionary, we will come out of the inner for loop using the break statement.

After checking if a key exists in the dictionary or not, we will move to the next key and repeat the same process. You can observe this in the following example.

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))

Output:

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.

Check if a Key Exists in a List of Dictionaries Using the for Loop

To check if a key exists in a list of dictionaries, we will first iterate over each dictionary in the list of dictionaries using a for loop. While iteration, we will use another for loop to check if the input key exists in the dictionary or not. Once we find that the key is present in a dictionary, we will print that the key is present in the list of dictionaries. After that, we will move out of the for loops using the break statement.

If none of the dictionaries in the list of dictionaries has the input key, we will print that the key doesn’t exist in the dictionary. You can observe this in the following example.

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))

Output:

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

Check if a Key Exists in a Dictionary Using the Membership Operator

The membership operator (in operator) is used to check if an element exists in a container object.

To check the presence of a key in a dictionary, we can use the in operator as shown below.

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))

Output:

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.

Check if Multiple Keys Exist in a Dictionary Using the Membership Operator

To check if multiple keys are present in the dictionary, we will use a for loop and the membership operator. We will iterate over the list of keys using the for loop. While iteration, we will check if a key is present in the dictionary using the membership operator. If we find that a key is present in the dictionary, we will say that the key exists in the dictionary. Otherwise not.

You can observe this in the following example.

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))

Output:

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.

Check if a Key Exists in a List of Dictionaries in Python Using the Membership Operator

Given a list of dictionaries, if we need to check if a key exists in a dictionary, we will use the following process.

We will iterate over the list of dictionaries using a for loop. While iteration, we will check if the key exists in each dictionary using the membership operator. If we don’t find the key in the present dictionary, we will move to the next dictionary. Once we find out that the key is present in the dictionary, we will print that the key exists in the dictionary. After that, we will move out of the loop using the break statement.

If we don’t find the key in any of the dictionaries, we will print that at the end. You can observe this in the following example.

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))

Output:

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

Check if a Key Exists in a Dictionary Using the keys() Method

The keys() Method

The keys() method, when invoked on a dictionary, returns a copy of the dict_keys object containing all the keys present in the dictionary as shown in the following python script.

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)

Output:

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

To check if a particular key exists in a dictionary using the keys() method, we will first obtain the dict_keys object. After that, we will iterate through the dict_keys object using a for loop. While iteration, we will check if the current key is the key that we are searching for. If yes, we will say that the key is present in the dictionary. Otherwise not. You can observe this in the following example.

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))

Output:

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.

Instead of using the for loop, we can also use the membership operator to check if the key exists in the dictionary as shown below.

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))

Output:

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.

Check if Multiple Keys Exist in a Dictionary Using the keys() Method

To check if multiple keys exist in a dictionary, we will iterate over the list of input keys. For each key, we will use the membership operator to check if the key exists in the dict_key object returned by the keys() method or not. If yes, we will print that the key is present in the dictionary. Otherwise, we will print that the key doesn’t exist. Finally, we will move to the next key. You can observe this in the following example.

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))

Output:

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.

Check if a Key Exists in a List of Dictionaries Using the keys() Method

To check if a key exists in a list of dictionaries using the keys() method, we will use the following procedure.

  • We will iterate over the list of dictionaries using a for loop.
  • While iterating over a dictionary, we will first obtain a list of keys of the dictionary using the keys() method. After that, we will use the membership operator to check if the input key is present in the list of keys.
  • If the key is present in the list, we will print so. After that, we will move out of the for loop using a break statement.
  • If we don’t find the key in the current list of keys, we will move to the next dictionary in the list of dictionaries using the continue statement.
  • After iterating over all of the dictionaries, if we don’t find the key, we will print that the key doesn’t exist in the dictionary.

You can observe the entire process in the following example.

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))

Output:

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

Check if a Key Exists in a Dictionary Using the viewkeys() Method

In python version 2.x, we can use the viewkeys() method instead of the keys method to check if a key exists in a dictionary.

The viewkeys() Method

The viewkeys() method, when invoked on a python dictionary, returns a view of the dict_key object containing the keys of the dictionary as shown below.

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)

Output:

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

To check if a specified key exists in a dictionary using the viewkeys() method, we will first obtain the dict_keys object using the viewkeys() method. After that, we will iterate through the dict_keys object using a for loop.

While iteration, we will check if the current key is the key that we are searching for. If yes, we will say that the key is present in the dictionary. Otherwise not. You can observe this in the following code.

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))

Output:

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.

Instead of using the for loop, we can also use the membership operator to check if the key exists in the dictionary as shown below.

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))

Output:

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.

Check if Multiple Keys Exist in a Dictionary Using the viewkeys() Method

To check if multiple keys exist in a dictionary using the viewkeys() method, we will iterate over the list of input keys.

For each key, we will use the membership operator to check if the key exists in the dict_keys object returned by the viewkeys() method or not. If yes, we will print that the key is present in the dictionary. Otherwise, we will print that the key doesn’t exist. Finally, we will move to the next key. You can observe this in the following example.

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))

Output:

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.

Check if a Key Exists in a List of Dictionaries Using the viewkeys() Method

To check if a key exists in a list of dictionaries using the viewkeys() method, we will use the following procedure.

  • We will iterate over the list of dictionaries using a for loop.
  • While iterating over a dictionary, we will first obtain the dict_keys object by invoking the viewkeys() method on the dictionary. After that, we will use the membership operator to check if the input key is present in the dict_keys object.
  • If the key is present in the dict_keys object, we will print so. After that, we will move out of the for loop using a break statement.
  • If we don’t find the key in the current dict_keys object, we will move to the next dictionary in the list of dictionaries using the continue statement.
  • After iterating over all of the dictionaries, if we don’t find the key, we will print that the key doesn’t exist in the list of dictionaries.

You can observe the entire process in the following example.

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))

Output:

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

Check if a Key Exists in a Dictionary Using the iterkeys() Method

In python version 2.x, we can also use the iterkeys() method instead of the viewkeys() method to check if a key exists in a dictionary.

The iterkeys() Method

The iterkeys() method, when invoked on a python dictionary, returns an iterator that iterates over the keys of the dictionary.

To check if a key exists in a dictionary using the iterkeys() method, we will first obtain the iterator by invoking the iterkeys() method on the dictionary. After that, we will iterate through the keys using a for loop and the iterator.

While iteration, we will check if the current key is the key that we are searching for. If yes, we will say that the key is present in the dictionary. Otherwise not. You can observe this in the following python program.

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))

Output:

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

Instead of using the for loop, you can use the membership operator and the iterkeys() method to check if a key exists in a dictionary as shown below.

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))

Output:

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

Check if Multiple Keys Exist in a Dictionary Using the iterkeys() Method

To check if multiple keys exist in a dictionary using the iterkeys() method, We will first obtain the iterator to the keys of the dictionary using the iterkeys() method. After that, we will iterate over the list of input keys.

For each key, we will use the membership operator to check if the key exists in the iterator object returned by the iterkeys() method or not. If yes, we will print that the key is present in the dictionary. Otherwise, we will print that the key doesn’t exist. Finally, we will move to the next key. You can observe this in the following example.

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))

Output:

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.

Check if a Key Exists in a List of Dictionaries Using the iterkeys() Method

To check if a key exists in a list of dictionaries using the iterkeys() method, we will use the following procedure.

  • We will iterate over the list of dictionaries using a for loop.
  • While iterating over a dictionary, we will first obtain the iterator to the keys of the dictionary by invoking the iterkeys() method on the dictionary. After that, we will use the membership operator to check if the input key is present in the iterator.
  • If the key is present in the iterator, we will print so. After that, we will move out of the for loop using a break statement.
  • If we don’t find the key in the current iterator, we will move to the next dictionary in the list of dictionaries using the python continue statement.
  • After iterating over all of the dictionaries, if we don’t find the key, we will print that the key doesn’t exist in the dictionary.

You can observe the entire process in the following example.

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))

Output:

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

Conclusion

In this article, we have discussed different ways to check if a key exists in a python dictionary. If you are working with python 3.x, out of all the methods, you should use the approach using the membership operator to check if a key exists in a dictionary or not. If you are working in python 2.x you can use the approach using the iterkeys() method to check if a given key exists in a dictionary. These two approaches are the fastest for the respective versions of python.

I hope you enjoyed reading this article. To learn more about python programming, you can read this article on how to remove all occurrences of a character in a list in Python. You might also like this article on how to check if a python string contains a number.

Stay tuned for more informative articles.

Happy learning!

The post Check if a Key Exists in a Dictionary in Python appeared first on PythonForBeginners.com.


Viewing all articles
Browse latest Browse all 22464

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>