user2956251
user2956251

Reputation: 37

How to check if dictionary has certain key (Python)

I'm having a defaultdict dictionary that has keys like this:

RJECNIK['*','A']['<A>']

now i don't know how to check if there is a key, for example:

a=list(RJECNIK.keys())

gives me the list of only first keys (['*','A']). In my code I need an if statement

if key in RJECNIK: ...

But it doesn't work since I don't know how to check for a PAIR of keys in defaultdict with 2 keys.

Upvotes: 1

Views: 486

Answers (3)

RemcoGerlich
RemcoGerlich

Reputation: 31260

You are using tuples as dictionary keys; '*', 'A' is just another way to spell the tuple ('*', 'A'). So

if ('*', 'A') in RJECNIK:

should be True.

Upvotes: 0

ford prefect
ford prefect

Reputation: 7388

From here: 'has_key()' or 'in'?

if ("*","A") in RJECNIK:
    print "key is in dictionary" 

According to this In what case would I use a tuple as a dictionary key? you should be fine

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122376

You need to check for both keys in both dictionaries:

key = ('*', '<A>')
if key[0] in RJECNIK and key[1] in RJECNIK[key[0]]:
    pass

Upvotes: 4

Related Questions