Thong Nguyen
Thong Nguyen

Reputation: 425

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.

Upvotes: 23

Views: 53388

Answers (2)

Hackaholic
Hackaholic

Reputation: 19733

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

Upvotes: 18

Chris_Rands
Chris_Rands

Reputation: 41168

The behavior you describe is correct because you create a new dict when you re-assign it to dict1 rather than modifying the existing dict, you can see this by tracking the identity of dict1:

>>> dict1 = {
... 'key1': 'value1',
... 'key2': 'value2',
... }
>>> 
>>> dict2 = {
... 'key1': 'value3',
... 'key2': 'value4',
... }
>>> 
>>> list = [dict1, dict2]
>>> dict1 in list
True
>>> id(dict1)
140141510806024
>>> dict1['newkey'] = 'value' # modify the dict
>>> id(dict1)
140141510806024 # the id has not changed
>>> dict1 in list
True
>>> dict1 = {
... 'key1': 'something',
... 'key2': 'value2',
... }
>>> id(dict1)
140141510059144 # the id has changed
>>> dict1 in list
False

Note don't use the variable name list because it shadows the in-built list().

Upvotes: 8

Related Questions