I have formed a dictionary with 2 keys assigning to a single dictionary value, for example:
my_dict[x, y] = ...
my_dict[a, u] = ...
Now how would i be able to use the has_key()
method for 2 key variables, x and y like such:
if my_dict.has_key(x,y) == True:
Do Something
else:
Do something else
d is a matrix, that uses pdict values that i call from a variable f and g, but all you need to know is that they are variable names x,y being used as key values in pdict.
To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.
How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.
In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values.
Since dict.has_key()
has been deprecated for a long time now, you should use the in
operator instead:
if (x, y) in my_dict:
# whatever
Note that your dictionary does not have "two keys". It probably uses a tuple
of two elements as a key, but that tuple is a single object.
If you used a sequence as a key like this:
d[1,2] = 3
the key is implicitly converted to a tuple. In a function call that expects a single argument, you need to specify the tuple explicitly:
d.has_key((1,2))
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