1

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.

3 Answers3

4

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
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • 1
    Seems like it could be generalised with `reduce` if the nesting is arbitrarily deep. – Marcin Nov 05 '13 at 15:41
  • Thank you very much, this worked! I may have confused you all, I should have made it more simple, but you got the point. – user2956251 Nov 05 '13 at 21:24
2

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

Community
  • 1
  • 1
ford prefect
  • 7,096
  • 11
  • 56
  • 83
0

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.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79