本文介绍了Python:检查列表元素是否是字典中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下代码
all_options = { "1": "/test/1", "2": "/test/2", "3": "/test/3" }
selected_options = [ "1", "3" ]
如何从 all_options 中获取条目,其中密钥与 selected_options 中的条目匹配?
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 ... ]
谢谢
推荐答案
就这样吗?
>>> dict((option, all_options[option]) for option in selected_options if option in all_options)
{'1': '/test/1', '3': '/test/3'}
或者如果您只想要的值:
Or if you just want the values:
>>> [all_options[option] for option in selected_options if option in all_options]
['/test/1', '/test/3']
这篇关于Python:检查列表元素是否是字典中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!