PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

One element of a tuple dict-key matching in Python

If I have a dict such as:

foo = {('foo', 45):5, ('bar', 34):3}

How can I check against part of that tuple?

if 'foo' in foo: #should be true
    pass
if 45 in foo: #also should be true

Or some other syntax.

Upvotes: 5

Views: 4191

Answers (3)

tokland
tokland

Reputation: 67900

>>> foo = {('foo', 45): 5, ('bar', 34): 3}    
>>> any(t1 == "foo" for (t1, t2) in foo)
True    
>>> any(t2 == 45 for (t1, t2) in foo)
True

If you don't know where the value is to be found you can just check the whole pair:

>>> any(45 in pair for pair in foo)
True

You can also a generators approach (flatten):

>>> 45 in flatten(foo)
True

That said, probably the best idea is to build your data so you can check this kind of inclussion in O(1) time (a set? a refactored dictionary?)

Upvotes: 7

rubik
rubik

Reputation: 9104

You can use operator.concat to flatten all keys:

>>> import operator
>>> 'foo' in reduce(operator.concat, foo.keys())
True

...or any:

any('foo' in t for t in foo.keys())

Upvotes: 1

steabert
steabert

Reputation: 6888

Another possibility using list comprehension:

if 'foo' in [key[0] for key in foo]:
  pass
if 45 in [key[1] for key in foo]:

Upvotes: 0

Related Questions