In this Python dictionary tutorial, we will discuss the Python dictionary contains. Here we will also cover the below examples:
- Python dictionary contains value
- Python dictionary contains Key
- Python dictionary contains list as value
- Python dictionary contains key example
- Python dictionary contains key value pair
- Python dictionary contains another dictionary
- Python dictionary contains element
- Python dictionary contains multiple keys
- Python dictionary contains duplicate keys
- Python dictionary key contains string
Python dictionary contains
- Let us see how to check if a key/value pair contains in the Python dictionary.
- The easiest way to check if a key/value pair exists in a dictionary is to use the in operator. To do this task we can specify key/value pairs in a Python tuple. To check if a key/value pair does not exist in the dictionary we can use not in operator.
Source Code:
my_dict = {"e":4,"l":6,"q":5}
print(('e', 4) in my_dict.items())
In the above code, we will first initialize a dictionary ‘my_dict’, assign a key-value element, and display the result.
Here is the execution of the following given code
Read: Python for loop index
Python dictionary contains value
- Here we can see how to check if the value contains in a Python dictionary.
- To solve this problem we can use values() and the if-in statement method. In Python, the values() method returns a view object that displays all the values connected with keys. To check if our value exists in the iterable sequence or not we can use the ‘in’ operator.
- There are various method to perform this task
- By using get and key method
- By using in operator
Syntax:
If value in dict:
# dictionary contains(True)
else:
# dictionary not contains
Source code:
The source code below represents the operation of the if-in statement to check if the value contains in a dictionary or not.
new_dict = {"Ethan":78,"Mason":98,"Benjamin":72}
new_val = 98
if new_val in new_dict.values():
print(f"True, Value contains in dictionary:",new_val)
else:
print(f"False, Value does not contains in dictionary:",new_val)
As you can see value ’98’ contains in a dictionary therefore the if-in statement comes true.
Here is the Screenshot of the following given code
Read Python ask for user input
By using get() and key method
In Python the get function accepts a key, In this case, the key is a built-in function in Python and it will always return the value of the given key. If the value does not contain in the dictionary it will return None.
Example:
ne_dictionary = {12:"OLiva",17:"Marry",16:"Gilchrist"}
key = 12
if ne_dictionary.get(key) == None:
print('Value not contain')
else:
print('Value contain')
Output:
By using in operator
Let us see how to check if the value contains in the Python dictionary by using in operator method.
Source Code:
ne_dictionary = {"q":12,"i":74,"p":23,"x":123}
print(74 in ne_dictionary.values())
.Here is the execution of the following given code
Read: Python dictionary comprehension
Python dictionary contains key
- To use in operator with if statement we can check whether the key is contained in a dictionary or not in Python.
- In Python, the in operator basically checks if a key contains in a dictionary or not. if the key does not exist we cannot use the in-operator.
- In this example, we will give the condition if the key exists the result will display ‘True’ otherwise if not exist it will return ‘False’.
Syntax:
If key in dict:
#key exist in dictionary (True)
else:
#key does not exist in dictionary(False)
Source Code:
my_dictionary = {"Samuel":19,"Mathew":37,"Micheal":92}
exist_ke = 'Potter'
if exist_ke in my_dictionary:
print("True, key contains in dict.\n" )
else:
print("False, key does not contains in dict.\n")
In the above code, you can see that we have used an if-in statement along with the operator. Now in this example, we do not have a ‘potter’ key in our dictionary, thus it will display the result ‘key does not contain in dict’.
Execution:
Another example to check if key contains in a dictionary using has_key() method
To check whether a particular key is present in the dictionary, we can easily use the function has_key(). This method returns true if the key exists otherwise it returns false.
Syntax:
dict.has_keys()
Note: In Python, the has_key() function is only available in Python 2.7 version.
Example:
country_dict = {"cuba":52,"Estonia":47,"Kenya":82}
new_key = 'Kenya'
if country_dict.has_key(new_key):
print("True, key contains:")
else:
print("False,key not contain")
Here is the output of the following given code
Read: Python dictionary find a key by value
Python dictionary contains list as value
Let us see how to check if the list as a value contains in the dictionary by using in operator method in Python.
Source code:
you_dict = {"o":[1,14,2,],"m":[10,74,90],"n":[23,47,86]}
print([10,74,90] in you_dict.values())
In the above code first, we will initialize a dictionary and assign their elements in the form of key-value pairs. But in this case, the value is in the list form. Now we will check the condition if the value contains in a dictionary or not.
Implementation:
Read: Python convert dictionary to list
Python dictionary contain key example
- let us see how to check if the key contains in a Python dictionary.
- To perform this task we can apply the python keys() method. This method helps the user to check if the key contains in an existing dictionary.
- This method takes no parameters and always returns a list of all the keys which is available in a dictionary. In this example, we can use the if- statement along with the keys() method to differentiate with the ‘new_key’ variable. If it is existing in the dictionary then it will display the result ‘True’ otherwise it will jump the statement in the else part and returns ‘False’.
Source Code:
stud_dict= {"Gayle":34,"Siemens":59,"pollard":70}
new_key = 'Siemens'
if new_key in stud_dict.keys():
print("True, it contains:")
else:
print("False, it does not contains")
Here is the Screenshot of the following given code
Another example to check if the key exists in a dictionary by using the get() method
In Python, the get() method accepts the only key parameter and returns the value along with the key. If the key does not exist in the dictionary by default it will return the None value.
Syntax:
dict.get
(
Key,
default=None
)
Example:
stud_dict= {"Oliver":943,"potter":178,"hemsworth":36}
se_ne_key = 'George'
if stud_dict.get(se_ne_key) == None:
print('Key not exist')
else:
print('Key exist')
Here is the implementation of the following given code
Read: Python dictionary remove
Python dictionary contains key-value pair
- Here we can see how to check if a key/value pair contains in a Python dictionary. The simplest way to check if a key/value pair exists in a dictionary is to use the in operator.
Example:
new_dict={'Brazil':63,'Bermuda':71,'Ireland':189}
new_key,new_value = 'Bermuda',71
z = new_key in new_dict and new_value == new_dict[new_key]
print("Keys and value exist in dictionary:",z)
Here is the execution of the following given code
Python dictionary contains another dictionary
- Here we can see if one dictionary is a subset of another dictionary in Python.
- To perform this task we can use the items() method along with <=operator. In Python, the items() method returns a list containing the key-value pair.
- The <= operator compares the values and returns the result in the form of ‘True’ or ‘False’.
Source Code:
Country_dict = {'Kuwait' : 523, 'Jordan' : 876, 'Laos' : 921, 'Libya' : 167, 'Malta' : 763}
sub_country = {'Jordan' : 876, 'Libya' : 167, 'Malta' : 763}
print("Country names:",Country_dict)
print("Another dictionary:",sub_country)
new_output = sub_country.items() <= Country_dict.items()
print("Dictionary contains in another dict: ",new_output)
Here is the Screenshot of the following given code
Read: Python dictionary length
Python dictionary contain elements
- To check if elements contain in a dictionary or not we can use the in operator in Python.
Example:
new_dictionary = {"z":18,"a":14,"c":10}
print(('a', 14) in new_dictionary.items())
Here is the implementation of the following given code
Read: Python Dictionary index
Python dictionary contains multiple keys
- Let us see how to check if multiple keys contained in a dictionary in Python.
- To perform this task we can easily use the issubset() method. This method is a in-built function in Python and it returns true if all the elements of dict1 are contained in original dictionary.
Code:
Food_dict = {"Italian" : 25, "Mexican" : 31, "Chinese" :27}
# multiple keys
new_dict = set(['Italian', 'Mexican'])
print(new_dict.issubset(Food_dict.keys()))
In the above code first, we will initialize a dictionary and declare a ‘new_dict’ variable and assign the set of keys that we want to compare and display the output.
Here is the implementation of the following given code
Read: Python dictionary initialize
Python dictionary contains duplicate keys
In Python to check if duplicate keys are contained in a dictionary. we can easily use the method chain and set(). This method takes a series of iterable items and returns a single iterable.
Source Code:
from itertools import chain
new_dictionary = {'m':87, 'a':29, 'q':29, 'w':34}
find_key = {}
for new_k, new_val in new_dictionary.items():
find_key.setdefault(new_val, set()).add(new_k)
output = set(chain.from_iterable(
new_val for new_k, new_val in find_key.items()
if len(new_val) > 1))
print("Duplicate values", output)
Here is the Screenshot of the following given code
Read: Python dictionary filter
Python dictionary key contains string
To perform this task we can apply the python keys() method in Python. This method helps the user check if the key contains a string in an existing dictionary.
Source Code:
new_dict= {"Andrew":146,"Hayden":190,"James":370}
new_key = 'Hayden'
if new_key in new_dict.keys():
print("True, string contains:")
else:
print("False, string does not contains")
Output:
You may also like to read:
- Python loop through a list
- Python copy file
- Python File methods
- Union of sets Python
- Python write a list to CSV
- Python dictionary popitem() method [With Examples]
In this Python tutorial, we have discussed the Python dictionary contains. Here we have also covered the following examples:
- Python dictionary contains value
- Python dictionary contains Key
- Python dictionary contains list as value
- Python dictionary contains key example
- Python dictionary contains key value pair
- Python dictionary contains another dictionary
- Python dictionary contains element
- Python dictionary contains multiple keys
- Python dictionary contains duplicate keys
- Python dictionary key contains string
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.