I have a list which contains some dicts:
dict1 = {
'key1': 'value1',
'key2': 'value2',
}
dict2 = {
'key1': 'value3',
'key2': 'value4',
}
list = [dict1, dict2]
I am using this to check if dict exists in list or not, for example I changed dict1
to this
dict1 = {
'key1': 'something',
'key2': 'value2',
}
Now, checking for dict1
if dict1 in list:
print('Exists')
else:
print('Not exists')
It must return 'Not exists'
, but it did not.
Using Keys() You can check if a key exists in a dictionary using the keys() method and IN operator. The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .
Use any() & List comprehension to check if a value exists in a list of dictionaries.
Check if Variable is a Dictionary with is Operator We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False .
Note
list
is a built-in function, use different name, such asmy_list
It returns False
as shown below:
>>> dict1
{'key2': 'value2', 'key1': 'value1'}
>>> my_list = [dict1, dict2]
>>> dict1 in my_list
True
>>> dict1 = {
... 'key1': 'something',
... 'key2': 'value2',
... }
>>> dict1 in my_list
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With