One tuple element associated with a key type in Python

If I have a dict, for example:

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

How can I check part of this tuple?

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

Or some other syntax.

+4
source share
3 answers
 >>> 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 located, you can simply check the whole pair:

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

You can also use a generator ( flatten ):

 >>> 45 in flatten(foo) True 

However, perhaps the best idea is to collect your data so that you can check this type of slope O (1) times (set? Reorganized dictionary?)

+7
source

You can use operator.concat to smooth out all the keys:

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

... or any:

 any('foo' in t for t in foo.keys()) 
+1
source

Another possibility to use the list:

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

Source: https://habr.com/ru/post/1342533/


All Articles