Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a dictionary exists in list

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.

like image 678
thoongnv Avatar asked May 01 '17 07:05

thoongnv


People also ask

How do you check if a dictionary exists in a list Python?

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 .

How do you check if a dictionary is in a list of dictionaries?

Use any() & List comprehension to check if a value exists in a list of dictionaries.

How do you check if a value is a dictionary Python?

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 .


1 Answers

Note list is a built-in function, use different name, such as my_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
like image 117
Hackaholic Avatar answered Sep 29 '22 14:09

Hackaholic