I have a Python dictionary as below:
d={ 'cs101': {'name': 'Building a Search Engine', 'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car', 'teacher': 'Sebastian',
'assistant': 'Andy'}
}
I need to find if the name ‘Peter’ is a teacher or assistant for any of these elements. Note that ‘Peter’ and ‘Peter C.’ are two different persons. Suppose coursename is a variable to loop through 'cs101' and 'cs373'. If I use ‘in’ keyword to check membership:
'Peter' in d[coursename]['assistant']
it will return True.
Similarly, '' in d[coursename]['assistant'] will also return True.
So, it seems that I cannot use the in keyword..
Can someone tell me how to check the membership?
Peter, where art thou?
'Peter' in 'Peter Pan'will check if the string ‘Peter’ can be found somewhere in ‘Peter Pan’, which is obviously true.If you want an exact match you should use
==, as in the below example:The above will do a case-sensitive match, if you’d like to do it case-insensitive you could write:
'Peter'.lower() == d[coursename]['assistant'].lower().Some examples of the differences between
inand==