Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check dict.has_key(k,x) with 2 variables

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.

like image 994
Sean Avatar asked Aug 06 '12 14:08

Sean


People also ask

How do you check if a key-value pair exists in a dictionary Python?

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 is 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.

How do you check all the values in a dictionary?

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.


2 Answers

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.

like image 164
Sven Marnach Avatar answered Oct 15 '22 22:10

Sven Marnach


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))
like image 31
chepner Avatar answered Oct 15 '22 22:10

chepner