Python | Get all tuple keys from dictionary

Python | Get all tuple keys from dictionary

To retrieve all the tuple keys from a dictionary in Python, you can use a list comprehension to filter out only those keys that are of type tuple. Here's how you can do this:

Given a dictionary:

dict_example = { (1, 2): 'a', (3, 4): 'b', 'string_key': 'c', (5, 6, 7): 'd', 'another_string_key': 'e' } 

To get all tuple keys:

tuple_keys = [key for key in dict_example.keys() if isinstance(key, tuple)] print(tuple_keys) 

Output:

[(1, 2), (3, 4), (5, 6, 7)] 

As shown in the output, only the keys that are tuples are retrieved from the dictionary.


More Tags

tax typescript2.0 worksheet docker-toolbox navigator melt pyspark http-status-code-304 key kotlin-null-safety

More Programming Guides

Other Guides

More Programming Examples