Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Check if any list element is a key in a dictionary

Given the following code

all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }
selected_options = [ "1", "3" ]

How do I get the entries from all_options where the key matches an entry in selected_options?

I started down the path of using a List Comprehension, but I'm stuck on the last clause:

final = ()
[ final.append(option) for option in all_options if ... ]

Thank you

like image 255
Misha M Avatar asked Jan 18 '23 21:01

Misha M


2 Answers

Just like this?

>>> dict((option, all_options[option]) for option in selected_options if option in all_options)
{'1': '/test/1', '3': '/test/3'}

From Python 2.7 and 3 onwards, you can use the dict comprehension syntax:

{option : all_options[option] for option in selected_options if option in all_options}

Or if you just want the values:

>>> [all_options[option] for option in selected_options if option in all_options]
['/test/1', '/test/3']
like image 120
Johnsyweb Avatar answered Jan 31 '23 07:01

Johnsyweb


[option for option in all_options if option in selected_options]

You may want to make a set of selected_options and use that instead if there are many.

like image 44
Ignacio Vazquez-Abrams Avatar answered Jan 31 '23 09:01

Ignacio Vazquez-Abrams